我有一个收集器,用于搜索游戏中的动作。我以递归搜索的方式进行搜索,以获取游戏中每一个可能的动作。
出于性能原因,我使用线程池,每个找到的移动都会向池中添加一个新线程,以扩展旧的移动。
这是一些代码:
protected static List<Runnable> threads;
private static ExecutorService threadPool;
protected final synchronized void hookThread(Runnable thread) {
if (threadPool == null) {
threadPool = Executors.newFixedThreadPool(15);
threads = new ArrayList<Runnable>();
}
threadPool.execute(thread);
threads.add(thread);
}
protected abstract class GathererRunnable implements Runnable {
@Override
public final void run() {
onRun();
threads.remove(this);
}
public abstract void onRun();
}
这是父类的一个片段。现在孩子来了,他正在寻找动作。
private void extendMove(final byte[] stones, final ByteLayMove move) {
Runnable r = new GathererRunnable() {
@Override
public void onRun() {
// fancy search stuff
if (moveIsFound)
extendMove(...);
}
};
hookThread(r);
}
现在的问题是,我不知道应该如何等待线程完成。
我尝试使用 int,它对线程创建进行计数,对线程完成进行计数,但这也会导致搜索过早中止。
您是否知道是否有一种等待这些线程的好方法?
我已经考虑过 BlockingQueue,但我不知道如何正确实现它。
问候凯文
下面的程序使用 BlockingQueue 实现了生产者消费者场景,您可以在编写自己的实现时使用这种方法。
import java.util.concurrent.*;
public class ThreadingExample {
public static void main(String args[]){
BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<Message>(100);
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Producer(blockingQueue));
exec.execute(new Consumer(blockingQueue));
}
}
class Message{
private static int count=0;
int messageId;
Message(){
this.messageId=count++;
System.out.print("message Id"+messageId+" Created ");
}
}
class Producer implements Runnable{
private BlockingQueue<Message> blockingQueue;
Producer(BlockingQueue<Message> blockingQueue){
this.blockingQueue=blockingQueue;
}
@Override
public void run(){
while(!Thread.interrupted()){
System.out.print("Producer Started");
try {
blockingQueue.put(new Message());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Producer Done");
}
}
}
class Consumer implements Runnable{
private BlockingQueue<Message> blockingQueue;
Consumer(BlockingQueue<Message> blockingQueue){
this.blockingQueue=blockingQueue;
}
@Override
public void run(){
while(!Thread.interrupted()){
System.out.print("Concumer Started");
try{
Message message = blockingQueue.take();
System.out.print("message Id"+message.messageId+" Consumed ");
}
catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Concumer Done");
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)