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類 下一篇:無