Java多线程等待线程完成

标签 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();

下面是 main 中发生的事情

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

我不希望 CSVpattern.run() 在 CSVcompare.run() 中的所有线程都完成之前启动,否则它将无法为 CSVpattern.run() 准备好某些数据

最佳答案

在运行结束时添加对 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()

关于Java多线程等待线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43151455/

相关文章:

java - 如何在不同的字符串之间共享子字符串?

c++ - 主机和目标的 Makefile

c++ - boost编译标志iw是什么意思?

c++ - 并行计算内存访问瓶颈

java - 在不阻塞整个数组的情况下更新数组元素

.net - 多线程应用程序中的 Entity Framework : Object not set exception in Oracle. DataAccess

java - Java 中的矩阵相加

java - HttpGet/客户端和 HTTPS

java - 将 Kinesis Client Library (KCL) 日志转储到文件

java - 如何将@Value注入(inject)到setter中?