Java線程中Thread方法下的Join方法詳解
等待線程執(zhí)行終止的join方法
在項目中往往會遇到這樣一個場景,就是需要等待幾件事情都給做完后才能走下面的事情。這個時候就需要用到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方法的時候,主線程就被被阻塞了,只有當調(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方法,當其他線程調(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主方法拋出了異常,這是因為在在調(diào)用ThreadOne線程,和ThreadTwo線程時線程one還在執(zhí)行中(死循環(huán)),這個時候main方法處于阻塞狀態(tài),當調(diào)用主方法的interrupt()方法后,Main方法已經(jīng)被阻塞了,所以就拋出了異常并返回了。
到此這篇關(guān)于Java線程中Thread方法下的Join方法詳解的文章就介紹到這了,更多相關(guān)Thread類下的Join方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java中如何把實體類轉(zhuǎn)成json格式的字符串
這篇文章主要介紹了java中如何把實體類轉(zhuǎn)成json格式的字符串問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12Springboot GET和POST請求參數(shù)獲取方式小結(jié)
Spring Boot GET和POST請求參數(shù)獲取是開發(fā)人員經(jīng)常需要解決的問題,本文主要介紹了Springboot GET和POST請求參數(shù)獲取方式小結(jié),具有一定的參考價值,感興趣的可以了解一下2023-09-09Spring Boot Event Bus用法小結(jié)
Spring Boot Event Bus是Spring框架中事件驅(qū)動編程的一部分,本文主要介紹了Spring Boot Event Bus用法小結(jié),感興趣的可以了解一下2023-09-09SpringBoot實現(xiàn)賬號登錄錯誤次數(shù)的限制和鎖定功能
本文介紹了如何使用SpringBoot和Redis實現(xiàn)賬號登錄錯誤次數(shù)限制和鎖定功能,通過自定義注解和AOP切面,結(jié)合配置文件靈活設置最大嘗試次數(shù)和鎖定時長,感興趣的朋友跟隨小編一起看看吧2024-12-12SpringBoot接口中如何直接返回圖片數(shù)據(jù)
這篇文章主要介紹了SpringBoot接口中如何直接返回圖片數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03