java – Thread.join()等效于执行器

前端之家收集整理的这篇文章主要介绍了java – Thread.join()等效于执行器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个新手的问​​题.我有这个代码
  1. public class Main
  2. {
  3.  
  4. public static void main(String[] args) throws InterruptedException
  5. {
  6. // TODO Auto-generated method stub
  7. IntHolder aHolder=new IntHolder();
  8. aHolder.Number=0;
  9.  
  10. IncrementorThread A= new IncrementorThread(1,aHolder);
  11. IncrementorThread B= new IncrementorThread(2,aHolder);
  12. IncrementorThread C= new IncrementorThread(3,aHolder);
  13.  
  14. A.start();
  15. B.start();
  16. C.start();
  17.  
  18. A.join();
  19. B.join();
  20. C.join();
  21. System.out.println("All threads completed...");
  22.  
  23. }
  24.  
  25. }

这将等待所有线程完成.如果我这样使用Executors:

  1. public class Main
  2. {
  3.  
  4. public static void main(String[] args)
  5. {
  6. // TODO Auto-generated method stub
  7. IntHolder aHolder=new IntHolder();
  8. aHolder.number=0;
  9.  
  10. IncrementalRunable A= new IncrementalRunable(1,aHolder);
  11. IncrementalRunable B= new IncrementalRunable(2,aHolder);
  12. IncrementalRunable C= new IncrementalRunable(3,aHolder);
  13.  
  14. ExecutorService exec = Executors.newFixedThreadPool(3);
  15. exec.execute(A);
  16. exec.execute(B);
  17. exec.execute(C);
  18. //Don't know what to do here
  19.  
  20. System.out.println("All threads completed...");
  21. }
  22. }

如何暂停主线程等待执行器中的所有线程完成,即所有线程完成工作后都应该打印“所有线程完成…”?

解决方法

  1. executor.shutdown();
  2. while (!executor.awaitTermination(24L,TimeUnit.HOURS)) {
  3. System.out.println("Not yet. Still waiting for termination");
  4. }

使用shutdown()awaitTermination()组合.

编辑:

基于@Lital的评论

  1. List<Callable<Object>> calls = new ArrayList<Callable<Object>>();
  2. calls.add(Executors.callable(new IncrementalRunable(1,aHolder)));
  3. calls.add(Executors.callable(new IncrementalRunable(2,aHolder)));
  4. calls.add(Executors.callable(new IncrementalRunable(3,aHolder)));
  5.  
  6. List<Future<Object>> futures = executor.invokeAll(calls);

注意:所有的任务完成(通过失败或完成成功执行),invokeAll()将不会返回.

猜你在找的Java相关文章