Java多线程等待线程完成

时间:2017-04-01 00:28:34

标签: java multithreading

尝试编写一个多线程的java程序,但遇到一些问题,我的主要多线程类工作正常,但如果我从main调用它启动所有线程并转到下一个函数,我需要它不要继续前进所有线程都完成了。 read获取传递的文件路径read(String,String)

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

准备好某些数据

1 个答案:

答案 0 :(得分: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()