Thread.join的用法&实现原理
1.作用:在当前线程内,等待目标线程执行完毕再执行(在当前线程内部调用join方法的线程执行完了后执行),把并行执行的任务,窜行化,保证执行顺序
2.代码举例
如main方法(它为当前线程),内部new 了三个线程,他们都调用了当前线程的join方法,那么会按当前调用join方法的先后顺序执行
注意:join方法必须在start启动之后设置才有效,并且必须在main方法的打印之前设置才能保证main的打印在thread1之后执行
因为main是方法的入口,先拿到cpu的执行权,它的总是优先的,所以必须在main有关的执行之前调用它的join方法才能使其让出执行权!
public class ThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() ->{
System.out.println("thread1");
});
Thread thread2 = new Thread(() ->{
System.out.println("thread2");
});
Thread thread3 = new Thread(() ->{
System.out.println("thread3");
});
thread1.start();
thread1.join(2);
System.out.println("我是主线程。。。"+Thread.currentThread().getName());
thread2.start();
thread2.join(2);
thread3.start();
thread3.join(2);
}
}
执行结果:
3.源码解析
join方法使用的是非静态的同步方法进行加锁,保证线程的执行顺序,join方法,内部不给等待时间默认是0,调用方法后让当前线程等待!设置了超时时间那么到时间了会自动释放锁,并调用notify方法唤起等待的线程
wait方法是调用的c语言,由c语言控制的这里就不再深究
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;
}
}
}