Java等待线程(Threadpool)完成工作并开始另一项工作

时间:2011-03-29 14:02:35

标签: java multithreading

所以我创建了让5个线程,并且在他们的工作完成之后,我想做另一项工作。那么如何找出执行者的线程何时完成他们的工作,然后才开始超级工作方法?

主要:

 ExecutorService executor = Executors.newFixedThreadPool(5);
   CountDownLatch doneSignal = new CountDownLatch(5);//thread number
   for(int i=0;i<5;i++){

   getLogFile n = new getLogFile(doneSignal, i);// work method

   executor.execute(n);
   doneSignal.await();  
   }

//可能在这里有类似executor.awaitTermination(60,TimeUnit.SECONDS); {不起作用}或者有效的东西

Superworkmethod(uses thread created files);//main thread probably starts thi

类别:

public static class getLogFile implements Runnable {
 private final CountDownLatch doneSignal;
   private final int i;
   getLogFile(CountDownLatch doneSignal, int i) {
      this.doneSignal = doneSignal;
      this.i = i;
   }

    public int run1(String Filenamet) {
    //do work
    }
    public void run() {
            run1(file);
            doneSignal.countDown();
    }

}

1 个答案:

答案 0 :(得分:6)

您可以使用ExecutorService.invokeAll()

ExecutorService executor = Executors.newFixedThreadPool(5);

List<Callable<Object>> tasks = new ArrayList<Callable<Object>>();    
for(int i=0;i<5;i++){
    tasks.add(Executors.callable(new getLogFile(doneSignal, i)));
}

executor.invokeAll(tasks);
// Here tasks are completed