Java并发学习之六——等待线程的终结
1、在某些情況下,我們需要等待線程的終結(jié)。例如,我們可能會(huì)遇到程序在執(zhí)行前需要初始化資源。在執(zhí)行剩下的代碼之前,我們需要等待線程完成初始化任務(wù)。為了達(dá)到此目的,我們使用Thread類的join()方法。當(dāng)前線程調(diào)用某個(gè)線程的這個(gè)方法時(shí),它會(huì)暫停當(dāng)前線程,直到被調(diào)用線程執(zhí)行完成。
2、Java提供2種形式的join()方法:
Join(longmilliseconds)
Join(long milliseconds,long nanos)
第一種join方法,讓調(diào)用線程等待特定的毫秒數(shù)。例如,如果thread1對(duì)象使用代碼thread2.join(1000),那么線程thread1暫停運(yùn)行,直到?以下其中一個(gè)條件發(fā)生:
Thread2結(jié)束運(yùn)行
1000毫秒過去了
當(dāng)其中一個(gè)條件為真時(shí),join()方法返回。
第二個(gè)版本的join方法和第一個(gè)很像,只不過它接收一個(gè)毫秒數(shù)和一個(gè)納秒數(shù)作為參數(shù)。
舉例如下:
package mytest; class Thread1 extends Thread { public Thread1(String threadName) { super(threadName); } public void run() { System.out.println(getName() + "is running"); try { sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread1 is over"); } } package mytest; class Thread2 extends Thread { private Thread1 thread1; public Thread2(String threadName, Thread1 thread1) { super(threadName); this.thread1 = thread1; } public void run() { System.out.println(getName() + "is running"); try { thread1.start(); thread1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread2 is over"); } } package mytest; public class JoinTest { public static void main(String[] args) { Thread1 thread1 = new Thread1("Thread1"); Thread2 thread2 = new Thread2("Thread2", thread1); thread2.start(); } }?
?
轉(zhuǎn)載于:https://www.cnblogs.com/pypua/articles/7243281.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Java并发学习之六——等待线程的终结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WCF双向通讯netTCP
- 下一篇: JavaWeb学习笔记九 过滤器、注解