Java線程中Thread方法下的Join方法詳解
等待線程執(zhí)行終止的join方法
在項(xiàng)目中往往會遇到這樣一個(gè)場景,就是需要等待幾件事情都給做完后才能走下面的事情。這個(gè)時(shí)候就需要用到Thread方法下的Join方法。join方法是無參且沒有返回值的。
package com.baidu.onepakage;
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
Thread theadOne = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("TheadOne run over");
});
Thread threadTwo = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("TheadTwo run over");
});
theadOne.start();
Thread.sleep(1000);
threadTwo.start();
System.out.println("main 開始啟動了");
theadOne.join();
threadTwo.join();
System.out.println("main 結(jié)束了");
}
}上面代碼在調(diào)用join方法的時(shí)候,主線程就被被阻塞了,只有當(dāng)調(diào)用join的方法執(zhí)行結(jié)束都才能夠接著往下面執(zhí)行。
執(zhí)行結(jié)果:
System.out.println(“TheadOne run over”);
System.out.println(“TheadTwo run over”);
System.out.println(“main 開始啟動了”);
System.out.println(“main 結(jié)束了”);
另外線程A調(diào)用線程B的join方法,當(dāng)其他線程調(diào)用了線程A的interrupt()方法,則A線程會拋出InterruptedException異常而返回。
示例:
package com.baidu.onepakage;
public class JoinTest01 {
public static void main(String[] args) {
Thread threadOne = new Thread(() -> {
for (; ; ) {
}
});
// 獲取主線程
Thread mainThread = Thread.currentThread();
// 線程2
Thread threadTwo = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 中斷主線程
mainThread.interrupt();
});
threadOne.start();
threadTwo.start();
try {
threadOne.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println(Thread.currentThread().getName() + "發(fā)生了異常");
}
}
}上面是Mian主方法拋出了異常,這是因?yàn)樵谠谡{(diào)用ThreadOne線程,和ThreadTwo線程時(shí)線程one還在執(zhí)行中(死循環(huán)),這個(gè)時(shí)候main方法處于阻塞狀態(tài),當(dāng)調(diào)用主方法的interrupt()方法后,Main方法已經(jīng)被阻塞了,所以就拋出了異常并返回了。
到此這篇關(guān)于Java線程中Thread方法下的Join方法詳解的文章就介紹到這了,更多相關(guān)Thread類下的Join方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
jcl與jul?log4j1?log4j2?logback日志系統(tǒng)機(jī)制及集成原理
這篇文章主要介紹了jcl與jul?log4j1?log4j2?logback的集成原理,Apache?Commons-logging?通用日志框架與日志系統(tǒng)的機(jī)制,有需要的朋友可以借鑒參考下2022-03-03
SpringMVC獲取HTTP中元素的實(shí)現(xiàn)示例
本文主要介紹了SpringMVC獲取HTTP中的元素,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-02-02
JAVA中JSONObject對象和Map對象之間的相互轉(zhuǎn)換
這篇文章主要介紹了JAVA中JSONObject對象和Map對象之間的相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Spring Boot 2.X整合Spring-cache(讓你的網(wǎng)站速度飛起來)
這篇文章主要介紹了Spring Boot 2.X整合Spring-cache(讓你的網(wǎng)站速度飛起來),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
使用Spring Data Jpa的CriteriaQuery一個(gè)陷阱
使用Spring Data Jpa的CriteriaQuery進(jìn)行動態(tài)條件查詢時(shí),可能會遇到一個(gè)陷阱,當(dāng)條件為空時(shí),查詢不到任何結(jié)果,并不是期望的返回所有結(jié)果。這是為什么呢?2020-11-11

