2011-03-29 50 views
4

因此,我創建可以說5個線程,並且在他們的工作完成後,我想要做另一項工作。那麼如何找出執行程序的線程什麼時候完成他們的工作,然後纔開始超級工作方法?Java等待線程(Threadpool)完成他們的工作並開始另一項工作

主營:

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(); 
    } 

}

回答

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 
+0

作用:tasks.add(Executors.callable(新getLogFile(doneSignal,I));一次執行每個線程或同時執​​行所有線程? ,因爲正在使用的j2ssh連接正在執行一項任務/在時間發送一個命令給服務器 – user615927 2011-03-30 10:58:00

+0

@ user615927:'invokeAll()'同時執行任務。如果你想要執行它們,爲什麼你需要線程池呢? – axtavt 2011-03-30 11:16:33

+0

我想我想讓事情變得比它本該更復雜(高水平的東西 - >工作更快),以同樣的方式結束),也認爲使用它會提高性能(許多小任務在同一時間單獨執行 - >速度)...無論如何,也許你知道如何停止主線程,直到其他線程完成他們的工作? – user615927 2011-03-30 13:44:54

相關問題