根据我对 join() 方法的理解,它允许一个线程等待另一个线程完成。
然后,根据我的代码:一旦线程(t0)结束,线程(t3)就应该启动,但这不会发生
public class Threaded extends Thread {
@Override
public void run() {
for (int i=0; i<5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
public class Demo {
public static void main(String[] args) throws InterruptedException {
Thread main = Thread.currentThread();
Threaded t0 = new Threaded();
Threaded t1 = new Threaded();
Threaded t2 = new Threaded();
Threaded t3= new Threaded();
t0.start();
t1.start();
t2.start();
t0.join();
t3.start();
}
}
输出为
main 5
Thread-1: 0
Thread-2: 0
Thread-0: 0
Thread-2: 1
Thread-2: 2
Thread-1: 1
Thread-2: 3
Thread-2: 4
Thread-0: 1
Thread-0: 2
Thread-0: 3
Thread-0: 4
Thread-1: 2
Thread-1: 3
Thread-1: 4
Thread-3: 0
Thread-3: 1
Thread-3: 2
Thread-3: 3
Thread-3: 4
在此输出中,Thread-3 在 Thread-0、Thread-1 和 Thread-2 结束后启动。 但是,根据我的说法,Thread-3 会在 Thread-0 结束后立即启动。
最佳答案
Thread-3 starts as soon as the Thread-0 ends.
Thread-0 完成后,Thread-3 即可运行。但这并不意味着立即安排。可能同时有 3 个可运行线程,并且无法预测哪个线程先打印。
关于java - join() 方法在多线程中如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54160399/