Java join()方法
线程类的
join()方法等待线程死亡。当您希望一个线程等待另一个线程完成时使用。这个过程就像接力赛,第二名选手一直等到第一名选手来,然后将旗帜交给他。
语法
public final void join()throws InterruptedException
public void join(long millis)throwsInterruptedException
public final void join(long millis, int nanos)throws InterruptedException
参数
millis: It defines the time to wait in milliseconds
nanos: 0-999999 additional nanoseconds to wait
返回
It does not return any value.
异常
IllegalArgumentException: 如果millis的值为负,或者nanos的值不在0-999999范围内,则抛出此异常。
InterruptedException: 如果任何线程中断了当前线程,则抛出此异常。抛出此异常时,将清除当前线程的中断状态。
示例1
public class JoinExample1 extends Thread
{
public void run()
{
for(int i=1; i<=4; i++)
{
try
{
Thread.sleep(500);
}
catch(Exception e){
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JoinExample1 t1 = new JoinExample1();
JoinExample1 t2 = new JoinExample1();
JoinExample1 t3 = new JoinExample1();
// thread t1 starts
t1.start();
// starts second thread when first thread t1 is died.
try
{
t1.join();
}
catch(Exception e){
System.out.println(e);
}
// start t2 and t3 thread
t2.start();
t3.start();
}
}
输出:
在上面的示例1中,当t1完成任务时,t2和t3开始执行。
示例2
public class JoinExample2 extends Thread
{
public void run()
{
for(int i=1; i<=5; i++)
{
try
{
Thread.sleep(500);
}
catch(Exception e){
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JoinExample2 t1 = new JoinExample2();
JoinExample2 t2 = new JoinExample2();
JoinExample2 t3 = new JoinExample2();
// thread t1 starts
t1.start();
// starts second thread when first thread t1 is died.
try
{
t1.join(1500);
}
catch(Exception e){
System.out.println(e);
}
// start t2 and t3 thread
t2.start();
t3.start();
}
}
输出:
1
2
3
1
1
4
2
2
5
3
3
4
4
5
5
在上面的示例2中,当t1完成其任务1500毫秒(3次)后,t2和t3开始执行。