【问题标题】:I just wonder why it have to join threads in the second loop我只是想知道为什么它必须在第二个循环中加入线程
【发布时间】:2026-02-15 23:55:01
【问题描述】:

写代码时:

public class TestBasic {

    public static void print(Object o){
        System.out.println(o);
    }

    public static void main(String...strings) throws InterruptedException {
        Thread[] threads = new Thread[5];
        for(int i=0;i<5;i++){
            Thread thread = new Thread(new LittleRunner());
            thread.start();
            thread.join();
        }
    }

}

class LittleRunner implements Runnable{
    public void run() {
        for(int i=1;i<10;i++){
            TestBasic.print(Thread.currentThread().getName()+":"+i);
        }
    }
}

输出是:

Thread-0:1
Thread-0:2
...
Thread-4:8
Thread-4:9

这意味着顺序打印出来。那么,有人知道原因吗?

非常感谢和最好的问候。

【问题讨论】:

    标签: java multithreading join


    【解决方案1】:

    您将加入每个线程在开始下一个线程之前
    在任何一个时间点,都只会有一个线程在运行,因为您已经在等待前一个线程完成。

    您需要在等待第一个线程完成之前启动所有线程。

    【讨论】:

    • 非常感谢,确实如此!就像我调用join时,主线程只是等待新创建的线程完成,然后下一个,下一个!
    【解决方案2】:

    将main方法改为:

    public static void main(String...strings) throws InterruptedException {
        Thread[] threads = new Thread[5];
        for(int i=0;i<5;i++){
            threads[i] = new Thread(new LittleRunner());
            threads[i].start();            
        }
        for(int i=0;i<5;i++){
            threads[i].join;            
        }
    }
    

    基本上,thread.start() 将在后台启动线程并继续前进。然后,当您执行 thread.join() 时,执行将停止,直到线程完成。因此,在您的程序版本中,您启动每个线程,然后等待它完成,然后再启动下一个线程,因此是顺序执行。

    【讨论】:

    • 加入线程是主线程,而不是其他线程,这是我忽略的问题!真可惜....谢谢,Raze2dust
    最近更新 更多