join()
在线程中调用另一个线程的join()方法,会将当前线程挂起,而不是忙等待,直到目标线程结束。
join()方法的源码
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;
}
}
}
不要在意源码细节,
可以看出的join()原理,即 使用wait()方法;
注意,join()方法被synchronized修饰,锁为this(当前真正运行的线程),能够执行join()方法的线程是已经获到锁并处于运行态,当运行到wait()时,线程由运行态转化为阻塞态 并释放锁;
有了wait(),必然有notify()
https://blog.csdn.net/u010983881/article/details/80257703
void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
// ...
// 就是这行
ensure_join(this);
// ...
}
static void ensure_join(JavaThread* thread) {
//...
// thread就是当前线程,就是刚才例子中说的this线程。
lock.notify_all(thread);
//...
}
使用例子
public class JoinExample {
static class A extends Thread {
@Override
public void run() {
System.out.println("A");
}
}
static class B extends Thread {
private A a;
B(A a) {
this.a = a;
}
@Override
public void run() {
try {
a.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
}
}
}
public static void main(String[] args) {
A a = new A();
B b = new B(a);
b.start();
a.start();
}
A、B线程同时运行,在B线程中调用A线程的join方法,会使B线程阻塞,直到A线程运行完才接直运行
A
B