Java并发学习之六——等待线程的终结
生活随笔
收集整理的這篇文章主要介紹了
Java并发学习之六——等待线程的终结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、在某些情況下,我們需要等待線程的終結。例如,我們可能會遇到程序在執行前需要初始化資源。在執行剩下的代碼之前,我們需要等待線程完成初始化任務。為了達到此目的,我們使用Thread類的join()方法。當前線程調用某個線程的這個方法時,它會暫停當前線程,直到被調用線程執行完成。
2、Java提供2種形式的join()方法:
Join(longmilliseconds)
Join(long milliseconds,long nanos)
第一種join方法,讓調用線程等待特定的毫秒數。例如,如果thread1對象使用代碼thread2.join(1000),那么線程thread1暫停運行,直到?以下其中一個條件發生:
Thread2結束運行
1000毫秒過去了
當其中一個條件為真時,join()方法返回。
第二個版本的join方法和第一個很像,只不過它接收一個毫秒數和一個納秒數作為參數。
舉例如下:
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(); } }?
?
轉載于:https://www.cnblogs.com/pypua/articles/7243281.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Java并发学习之六——等待线程的终结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WCF双向通讯netTCP
- 下一篇: 【BZOJ4476】[Jsoi2015]