2017-04-01 169 views
0

試圖編寫一個多線程的Java程序,但遇到一些問題,我的主要多線程類可以正常工作,但如果我從main調用它啓動所有線程並移動到下一個函數,我需要它不動,直到完成所有線程。讀被傳遞文件路徑讀取(字符串,字符串)Java多線程等待線程完成

  Thread one = new Thread(new Runnable() { 
       public void run() 
       { 
        System.out.println("Starting thread 1"); 
        read(expiredOneYear, master1); 
        System.out.println("Finished thread 1"); 
       } 
      }); 

      Thread two = new Thread(new Runnable() { 
       public void run() 
       { 
        System.out.println("Starting thread 2"); 
        read(expiredOneAndQuarterYear, master2); 
        System.out.println("Finished thread 2"); 
       } 
      }); 

      Thread three = new Thread(new Runnable() { 
       public void run() 
       { 
        System.out.println("Starting thread 3"); 
        read(expiredOneAndHalfYear , master3); 
        System.out.println("Finished thread 3"); 
       } 
      }); 

      Thread four = new Thread(new Runnable() { 
       public void run() 
       { 
        System.out.println("Starting thread 4"); 
        read(expiredOneAnd3QuarterYear , master4); 
        System.out.println("Finished thread 4"); 
       } 
      }); 

      // start threads 
      one.start(); 
      two.start(); 
      three.start(); 
      four.start(); 
下面

是主要

CSVcompare.run(threadCount, mode, fileLocation); 
CSVpattern.run(fileLocation); 

發生什麼事,我不想CSVpattern.run()開始在CSVcompare.run直到所有線程()已完成,否則將不會有某些數據準備好用於CSVpattern.run()

+0

你真的需要** ** CountDownLatch這裏。您的方案完全符合coundownlatch的使用。 – vijayraj34

回答

1

在運行結束時將呼叫添加到join()join()方法等待線程完成。

try 
{ 
    one.join(); 
    two.join(); 
    three.join(); 
    four.join(); 
} 
catch (InterruptedException e) 
{ 
    System.out.println("Interrupt Occurred"); 
    e.printStackTrace(); 
} 

如果你想忽略中斷(可能至少應該弄清楚它爲什麼被中斷,但是這將工作)

boolean done = false; 
while (!done) 
{ 
    try 
    { 
     one.join(); 
     two.join(); 
     three.join(); 
     four.join(); 
     done = true; 
    } 
    catch (InterruptedException e) 
    { 
     // Handle interrupt determine if need to exit. 
    } 
} 

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()

+0

所以添加下面的one.run();我這樣做,並得到一個錯誤未處理的異常類型InterruptedException,我使用Eclipse btw – user3058423

+0

@ user3058423如果在等待線程完成時發生中斷,那麼連接可以拋出InterruptedException。把代碼放在'try/catch'來處理它。我會編輯答案。 – twain249

+0

我認爲第一個更新的答案有效,我做了一個帶有代碼的簡單版本,以查看它是否有效,它做了什麼,我目前無法進行全面測試,因爲它實際上需要花費數小時來運行數據 – user3058423