Java Thread join()方法

Thread类的join()方法等待线程死亡。当希望一个线程等待另一个线程完成时使用它。 这个过程就像一场接力赛,第二个跑步者等到第一个跑步者来到并将旗帜移交给他。

语法

public final void join()throws InterruptedException  
public void join(long millis)throwsInterruptedException  
public final void join(long millis, int nanos)throws InterruptedException

参数

  • millis:它定义等待的时间,以毫秒为单位。
  • nanos0-999999等待的额外纳秒。

异常

  • IllegalArgumentException:如果millis的值为负,或者nanos的值不在0-999999范围内,则抛出此异常
  • InterruptedException:如果任何线程中断了当前线程,则抛出此异常。 抛出此异常时,将清除当前线程的中断状态。

示例一

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
2
3
4
1
1
2
2
3
3
4
4

在上面的示例1 中,当t1完成其任务时,t2t3开始执行。

示例二

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次)后,然后t2t3开始执行。


上一篇: Java Runtime类 下一篇:无