線程類的 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 toString()用法及代碼示例
- Java Thread interrupted()用法及代碼示例
- Java Thread setDefaultUncaughtExceptionHandler()用法及代碼示例
- Java Thread suspend()用法及代碼示例
- Java Thread destroy()用法及代碼示例
- Java Thread holdLock()用法及代碼示例
- Java Thread getContextClassLoader()用法及代碼示例
- Java Thread setContextClassLoader()用法及代碼示例
- Java Thread sleep()用法及代碼示例
- Java Thread getThreadGroup()用法及代碼示例
- Java Thread isInterrupted()用法及代碼示例
- Java Thread enumerate()用法及代碼示例
- Java Thread notify()用法及代碼示例
- Java Thread resume()用法及代碼示例
- Java Thread activeCount()用法及代碼示例
- Java Thread isDaemon()用法及代碼示例
- Java Thread setDaemon()用法及代碼示例
- Java Thread getId()用法及代碼示例
- Java Thread setName()用法及代碼示例
- Java Thread getDefaultUncaughtExceptionHandler()用法及代碼示例
注:本文由純淨天空篩選整理自 Java Thread join() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。