日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java并发学习之六——等待线程的终结

發(fā)布時(shí)間:2024/4/17 java 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java并发学习之六——等待线程的终结 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1、在某些情況下,我們需要等待線程的終結(jié)。例如,我們可能會(huì)遇到程序在執(zhí)行前需要初始化資源。在執(zhí)行剩下的代碼之前,我們需要等待線程完成初始化任務(wù)。為了達(dá)到此目的,我們使用Thread類的join()方法。當(dāng)前線程調(diào)用某個(gè)線程的這個(gè)方法時(shí),它會(huì)暫停當(dāng)前線程,直到被調(diào)用線程執(zhí)行完成。

2Java提供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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。