我有一个线程池,它为我执行线程,当我传递的所有线程都完成时,我怎么知道呢?
例如:
main.java
for (int i = 0; i < objectArray.length; i++) {
threadPool.submit(new ThreadHandler(objectArray[i], i));
Thread.sleep(500);
}ThreadHandler.java
public class ThreadHandler implements Runnable {
protected SuperHandler HandlerSH;
protected int threadNum;
public ThreadHandler(SuperHandler superH, int threadNum) {
this.threadNum = threadNum;
this.HandlerSH = superH;
}
public void run() {
//do all methods here
}我会把一些东西放到run()部分中来设置布尔值吗?我会做一个布尔数组来检查它们什么时候都完成了吗?
谢谢。
发布于 2013-01-30 15:34:40
当您将作业提交到线程池时,它将返回一个 instance。您可以打电话给Future.get(),查看工作是否已经完成。这实际上类似于线程池中运行的任务的联接。
如果线程池已经关闭,并且希望等待所有任务完成,也可以调用threadPool.awaitTermination(...)。
通常,当我将许多工作提交到线程池中时,我会将它们的未来记录在一个列表中:
List<Future<?>> futures = new ArrayList<Future<?>>();
for (int i = 0; i < objectArray.length; i++) {
futures.add(threadPool.submit(new ThreadHandler(objectArray[i], i)));
}
// if we are done submitting, we shutdown
threadPool.shutdown();
// now we can get from the future list or awaitTermination
for (Future<?> future : futures) {
// this throws an exception if your job threw an exception
future.get();
}https://stackoverflow.com/questions/14607687
复制相似问题