目录
自己写了一段main方法代码,试验过N次,暂时未发现问题。
自己的理解(如果错误,请大佬们指导一下):
使用线程的join方法,让线程进行等待,join()方法实际跟调用join(0)效果一致,参数代表的是等待线程执行的时间,单位是毫秒。
设置为0并不代表不等待,而是一直等待,直到调用isAlive方法返回true,表示当前线程执行完成;否则继续等待(串发执行)。
如果设置的等待时间为负数,直接报错,如果为正数,前一个线程会等待xx.join的xx这个线程正数的时间后继续执行(并发执行)。
join源码如下:
join()方法
public final void join() throws InterruptedException {
join(0);
}
join(long)方法
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;
}
}
}
测试代码如下:
public static void main(String[] args) {
Thread t1 = new Thread(() ->{
for (int i =0; i < 10; i++) {
System.out.println("I‘m Thread one:" + i);
}
});
Thread t2 = new Thread(() -> {
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i =0; i < 10; i++) {
System.out.println("I‘m Thread two:" + i);
}
});
Thread t3 = new Thread(() -> {
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i =0; i < 10; i++) {
System.out.println("I‘m Thread three:" + i);
}
});
t1.start();
t3.start();
t2.start();
}