join()方法的java代码如下
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
因此,根据此,每当我们调用 someThreadobj.join() 时,该线程都会获得锁并进入等待状态。那么为什么当我从主线程调用它时会让主线程等待。
这就是我正在测试的
public class Test {
volatile int i = 10;
public static void main(String[] args) throws InterruptedException {
Test obj = new Test();
Thread th1 = new Thread(() -> {
for (int j = 0; j < 10; j++) {
try {
Thread.sleep(2000);
System.out.println("Inside Thread ... " + Thread.currentThread().getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread th2 = new Thread(() -> {
for (int j = 0; j < 10; j++) {
try {
Thread.sleep(2000);
System.out.println("Inside Thread ... " + Thread.currentThread().getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread th3 = new Thread(() -> {
for (int j = 0; j < 10; j++) {
try {
Thread.sleep(2000);
System.out.println("Inside Thread ... " + Thread.currentThread().getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
th1.start();
th1.join();
th2.start();
th2.join();
th3.start();
}
}
Output
Inside Thread ... Thread-0
Inside Thread ... Thread-0
Inside Thread ... Thread-0
Inside Thread ... Thread-0
Inside Thread ... Thread-1
Inside Thread ... Thread-1
Inside Thread ... Thread-1
Inside Thread ... Thread-1
Inside Thread ... Thread-1
Inside Thread ... Thread-2
Inside Thread ... Thread-2
Inside Thread ... Thread-2
Inside Thread ... Thread-2
Inside Thread ... Thread-2
主线程不应该立即启动所有线程吗?
最佳答案
Shouldn't the main thread would have started all the thread at once.
不,因为在前面的线程完成之前您没有启动后续线程,因为您在对 start
的调用之间使用了 join
,并且 join
使主线程等待,直到您调用的 join
完成。线程构造函数只是创建线程对象,并不启动线程。
如果您希望同时启动所有线程,请调用 start
而无需在中间调用 join
。
th1.start();
th2.start();
th3.start();
th1.join();
th2.join();
th3.join(); // (This one was missing)
关于java - 调用 java Thread join() 方法如何使外部线程等待,而它本应是调用 join() 的线程本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57739049/