一)join()简介
void join():等待这个线程终止。
void join(long millis):等待这个线程终止最多 millis毫秒。
void join(long millis, int nanos):等待最多 millis毫秒加上 nanos纳秒这个线程终止。
线程终止:该线程终止指的是主线程等待子线程的终止。也就是说子线程调用了join()方法时,该方法后面的代码,只有等到子线程结束了才能执行。
线程加入:在当前线程调用join方法时,会使线程变为阻塞状态,直到另一线程运行结束,当前线程阻塞状态变为就绪状态。
适用场景:当主线程启动子线程时,如子线程计算耗时比较久,主线程会优先子线程结束,但当主线程处理完事务,需要用到子线程的处理结果,该场景就需要等待子线程结束,再执行主线程。
二)join()
jdk中join()方法源码:
public final void join() throws InterruptedException {
join(0);
}
public final synchronized void join(long millis) throws InterruptedException {
long base = System.currentTimeMillis(); // 当前毫秒时间
long now = 0;
if (millis < 0) { // 指定毫秒数小于0时, 抛异常
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) { // 当毫秒数为0时
while (isAlive()) { // 判断线程是否属于激活状态
wait(0); // 一直等待
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
public final synchronized void join(long millis, int nanos) throws InterruptedException {
if (millis < 0) { // 指定毫秒数小于0时, 抛异常
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException("nanosecond timeout value out of range");
}
if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
millis++;
}
join(millis); // 指定毫秒数
}
join()案例:
public class JoinRunnable implements Runnable {
private Thread thread;
private String threadName;
public JoinRunnable(String threadName) {
this.threadName = threadName;
}
public void run() {
try {
for(int i=0; i<5; i++) {
System.out.println("Thread Name: " + threadName + ", i = " + i);
Thread.sleep((int)(Math.random()*100));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void start() {
if (thread == null) {
thread = new Thread(this, threadName);
thread.start();
}
}
public void join() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
未使用join()时:
public class Main {
public static void main(String[] args) {
System.out.println("-->main主线程启动");
JoinRunnable r1 = new JoinRunnable("A");
JoinRunnable r2 = new JoinRunnable("B");
r1.start();
r2.start();
System.out.println("-->main主线程结束");
}
}
运行结果:
结果说明:当程序启动时,启动了一个main线程,两个AB子线程,main线程优先子线程执行完。
使用join()时:
public class Main {
public static void main(String[] args) {
System.out.println("-->main主线程启动");
JoinRunnable r1 = new JoinRunnable("A");
JoinRunnable r2 = new JoinRunnable("B");
r1.start();
r2.start();
r1.join();
r2.join();
System.out.println("-->main主线程结束");
}
}
运行结果:
结果说明:当程序启动时,启动了一个main线程,两个AB子线程,由于子线程调用了join()方法,所以主线程会等待子线程执行完之后才执行。
识别二维码关注个人微信公众号
本章完结,待续,欢迎转载!
本文说明:该文章属于原创,如需转载,请标明文章转载来源!