当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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

在上面的示例 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 开始执行。







相关用法


注:本文由纯净天空筛选整理自 Java Thread join() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。