传送门:https://www.cnblogs.com/techyc/p/3286678.html(本篇文章部分摘自这里)
join()是Thread类的一个方法。根据jdk文档的定义:
public final void join()throws InterruptedException: Waits for this thread to die.
join()方法的作用,是等待这个线程结束;但显然,这样的定义并不清晰。个人认为"Java 7 Concurrency Cookbook"的定义较为清晰:
join() method suspends the execution of the calling thread until the object called finishes its execution.
也就是说,t.join()方法阻塞调用此方法的线程(calling thread),直到线程t完成,此线程再继续;通常用于在main()主线程内,等待其它线程完成再结束main()主线程。例如:
/***************************可不看**********************************/
class MyThread implements Runnable {
Thread thrd;
MyThread(String name)
{
thrd = new Thread(this, name);
thrd.start();
}
public void run()
{
System.out.println(thrd.getName() + " starting");
try {
for(int count = 0; count < 10; count++)
{
Thread.sleep(400);
System.out.println("IN" + thrd.getName() + ", count is " + count);
}
}catch(InterruptedException exc)
{
System.out.println(thrd.getName() + " interrupted ");
}
System.out.println(thrd.getName() + " terminating ");
}
}
/***************************************************************************/
class UseJoin
{
public static void main(String []args)
{
System.out.println("Main thread starting.");
MyThread mt7 = new MyThread("Child #7");
MyThread mt8 = new MyThread("Child #8");
MyThread mt9 = new MyThread("Child #9");
try {
mt7.thrd.join();
System.out.println(mt7.thrd.getName()+" joined.");
mt8.thrd.join();
System.out.println(mt8.thrd.getName()+" joined.");
mt9.thrd.join();
System.out.println(mt9.thrd.getName()+" joined.");
}catch(InterruptedException exc)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread ending");
}
}
打印结果:
Main thread starting.
Child #9 starting
Child #8 starting
Child #7 starting
INChild #8, count is 0
INChild #9, count is 0
INChild #7, count is 0
INChild #8, count is 1
INChild #7, count is 1
INChild #9, count is 1
INChild #8, count is 2
INChild #7, count is 2
INChild #9, count is 2
INChild #7, count is 3
INChild #9, count is 3
INChild #8, count is 3
INChild #8, count is 4
INChild #7, count is 4
INChild #9, count is 4
INChild #9, count is 5
INChild #8, count is 5
INChild #7, count is 5
INChild #8, count is 6
INChild #7, count is 6
INChild #9, count is 6
INChild #7, count is 7
INChild #8, count is 7
INChild #9, count is 7
INChild #8, count is 8
INChild #9, count is 8
INChild #7, count is 8
INChild #8, count is 9
INChild #9, count is 9
Child #9 terminating
INChild #7, count is 9
Child #7 terminating
Child #8 terminating
Child #7 joined.
Child #8 joined.
Child #9 joined.
Main thread ending
所以,我觉得这句话就可以解释为什么结果是这个了