执行器中的Thread.join()等价物
我有一个新手问题。 我有这个代码:
public class Main { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub IntHolder aHolder=new IntHolder(); aHolder.Number=0; IncrementorThread A= new IncrementorThread(1, aHolder); IncrementorThread B= new IncrementorThread(2, aHolder); IncrementorThread C= new IncrementorThread(3, aHolder); A.start(); B.start(); C.start(); A.join(); B.join(); C.join(); System.out.println("All threads completed..."); } }
这将等待所有线程完成。 如果我像这样使用Executors
:
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub IntHolder aHolder=new IntHolder(); aHolder.number=0; IncrementalRunable A= new IncrementalRunable(1, aHolder); IncrementalRunable B= new IncrementalRunable(2, aHolder); IncrementalRunable C= new IncrementalRunable(3, aHolder); ExecutorService exec = Executors.newFixedThreadPool(3); exec.execute(A); exec.execute(B); exec.execute(C); //Don't know what to do here System.out.println("All threads completed..."); } }
如何挂起主线程以等待执行程序中的所有线程完成,即在所有线程完成工作后应打印“所有线程完成…”?
executor.shutdown(); while (!executor.awaitTermination(24L, TimeUnit.HOURS)) { System.out.println("Not yet. Still waiting for termination"); }
使用shutdown() + awaitTermination()
组合。
编辑:
根据@Lital的评论
List> calls = new ArrayList>(); calls.add(Executors.callable(new IncrementalRunable(1, aHolder))); calls.add(Executors.callable(new IncrementalRunable(2, aHolder))); calls.add(Executors.callable(new IncrementalRunable(3, aHolder))); List> futures = executor.invokeAll(calls);
注意: invokeAll()
将不会返回,直到完成所有任务(通过失败或完成成功执行)。
如果要等待任务完成,则不应使用此类执行程序。 如果您不希望/无法关闭线程池执行程序,该怎么办? 这是一种更推荐的方式:
ExecutorService exec = Executors.newFixedThreadPool(3); Collection> tasks = new LinkedList>(); Future future = exec.submit(A); tasks.add(future); future = exec.submit(B); tasks.add(future); future = exec.submit(C); tasks.add(future); // wait for tasks completion for (Future> currTask : tasks) { try { currTask.get(); } catch (Throwable thrown) { Logger.error(thrown, "Error while waiting for thread completion"); } }
尝试以这种方式使用线程池。
executor.shutdown(); executor.awaitTermination(MAX_PRIORITY, TimeUnit.HOURS);
exec.shutdown(); // Wait until all threads are finish exec.awaitTermination();
- Java:带有Callables的ExecutorService:invokeAll()和future.get() – 结果是否正确?
- 删除ThreadPoolExecutor的所有排队任务
- 什么是Java中最快的循环同步(ExecutorService与CyclicBarrier vs.X)?
- 线程终止时的Java ExecutorService回调
- 如何等待一个产生它自己的线程的线程?
- shutdown和awaitTermination哪个第一次调用有什么区别?
- 超出范围时,ExecutorService是否会收集垃圾?
- 如何使用invokeAll()让所有线程池完成他们的任务?
- 如何在java中设置Socket写入时间?