【发布时间】:2014-04-24 21:06:48
【问题描述】:
我有一个收集器,用于搜索游戏中的动作。我在递归搜索中搜索,以获取游戏中所有可能的动作。
出于性能原因,我使用了一个线程池,并且每个找到的动作都会向池中添加一个新线程,以可能扩展旧动作。
这里有一些代码:
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();
}
这是父类的sn-p。现在孩子来了,它正在寻找动作。
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,但我不知道如何正确实现它。
问候凯文
【问题讨论】:
-
您使用的是AtomicInteger 还是普通的
int?后者不起作用,但第一个应该(使用方法incrementAndGet和decrementAndGet)。 -
ArrayList线程安全吗?
标签: java multithreading recursion