publicclassTestThreadextendsThread
{
publicvoidrun()
{
System.out.println(this.getName() +"子线程开始");
try
{
// 子线程休眠五秒
Thread.sleep(5000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(this.getName() +"子线程结束");
}
}
首先是一个线程,它执行完成需要5秒。
1、主线程等待一个子线程
publicclassMain
{
publicstaticvoidmain(String[] args)
{
longstart = System.currentTimeMillis();
Thread thread = newTestThread();
thread.start();
longend = System.currentTimeMillis();
System.out.println("子线程执行时长:"+ (end - start));
}
}
在主线程中,需要等待子线程执行完成。但是执行上面的main发现并不是想要的结果:
子线程执行时长:0
Thread-0子线程开始
Thread-0子线程结束
很明显主线程和子线程是并发执行的,主线程并没有等待。
对于只有一个子线程,如果主线程需要等待子线程执行完成,再继续向下执行,可以使用Thread的join()方法。join()方法会阻塞主线程继续向下执行。
publicclassMain
{
publicstaticvoidmain(String[] args)
{
longstart = System.currentTimeMillis();
Thread thread = newTestThread();
thread.start();
try
{
thread.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
longend = System.currentTimeMillis();
System.out.println("子线程执行时长:"+ (end - start));
}
}
执行结果:
Thread-0子线程开始
Thread-0子线程结束
子线程执行时长:5000
注意:join()要在start()方法之后调用。
2、主线程等待多个子线程
比如主线程需要等待5个子线程。这5个线程之间是并发执行。
publicclassMain
{
publicstaticvoidmain(String[] args)
{
longstart = System.currentTimeMillis();
for(inti =0; i <5; i++)
{
Thread thread = newTestThread();
thread.start();
try
{
thread.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
longend = System.currentTimeMillis();
System.out.println("子线程执行时长:"+ (end - start));
}
}
在上面的代码套上一个for循环,执行结果:
Thread-0子线程开始
Thread-0子线程结束
Thread-1子线程开始
Thread-1子线程结束
Thread-2子线程开始
Thread-2子线程结束
Thread-3子线程开始
Thread-3子线程结束
Thread-4子线程开始
Thread-4子线程结束
子线程执行时长:25000
由于thread.join()阻塞了主线程继续执行,导致for循环一次就需要等待一个子线程执行完成,而下一个子线程不能立即start(),5个子线程不能并发。
要想子线程之间能并发执行,那么需要在所有子线程start()后,在执行所有子线程的join()方法。
publicclassMain
{
publicstaticvoidmain(String[] args)
{
longstart = System.currentTimeMillis();
List list = newArrayList();
for(inti =0; i <5; i++)
{
Thread thread = newTestThread();
thread.start();
list.add(thread);
}
try
{
for(Thread thread : list)
{
thread.join();