Thread 的join的作用是将thread 加入到当前的线程
看个例子就很好理解了
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("thread1 IM work");
Thread.sleep(5000);
System.out.println("thread1 IM done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("thread2 IM work");
Thread.sleep(10000);
System.out.println("thread2 IM done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
System.out.println("IM done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
一共三个线程 一个父线程thread 两个子线程 thread1 ,thread2。
输出日志
thread1 IM work
thread2 IM work
thread1 IM done
thread2 IM done
IM done
thread1.join();
thread2.join();
是将thread1 thread2 加入到thread 父线程 ,thread会等待两个子线程完成,thread.join() 是加入当前main所在的线程 ,所以IM done 是所有线程运行完之后才打印的。
可以测试分别把
thread.join()和
thread1.join();
thread2.join();
去掉 看下打印的日志就知道区别了