歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java線程join示例詳解

Java線程join示例詳解

日期:2017/3/1 9:43:38   编辑:Linux編程

Java線程的join方法可用於暫停當前線程的執行直至目標線程死亡。Thread中一共有三個join的重載方法。

public final void join():該方法將當前線程放入等待隊列中,直至被它調用的線程死亡為止。如果該線程被中斷,則會拋出InterruptedException異常。

public final synchronized void join(long millis):該方法用於讓當前線程進入等待狀態,直至被它調用的線程死亡或是經過millis毫秒。由於線程的執行依賴於操作系統,所以該方法無法保證當前線程等待的時間和指定時間一致。

public final synchronized void join(long millis, int nanos):該方法用於讓線程暫停millis毫秒nanos納秒。

Java 8 中 HashMap 的性能提升 http://www.linuxidc.com/Linux/2014-04/100868.htm

Java 8 的 Nashorn 引擎 http://www.linuxidc.com/Linux/2014-03/98880.htm

Java 8簡明教程 http://www.linuxidc.com/Linux/2014-03/98754.htm

下面的例子演示了join方法的使用。該段代碼的目的是確保main線程最後結束,並且僅當第一個線程死亡才能啟動第三個線程。

ThreadJoinExample.java

package com.journaldev.threads;
public class ThreadJoinExample {
Thread t1 = new Thread(new MyRunnable(), "t1");
Thread t2 = new Thread(new MyRunnable(), "t2");
Thread t3 = new Thread(new MyRunnable(), "t3");

t1.start();

//start second thread after waiting for 2 seconds or if it's dead
try {
t1.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

t2.start();

//start third thread only when first thread is dead
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

t3.start();

//let all threads finish execution before finishing main thread
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("All threads are dead, exiting main thread");
}

class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread started:::" + Thread.currentThread.getName());
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Thread ended:::" + Thread.currentThread.getName());
}
}

Copyright © Linux教程網 All Rights Reserved