2017-04-01 171 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