Java線(xiàn)程狀態(tài)變換過(guò)程代碼解析
線(xiàn)程狀態(tài)
NEW:剛創(chuàng)建未啟動(dòng)的線(xiàn)程 RUNNABLE:正在執(zhí)行狀態(tài) BLOCKED:處于阻塞狀態(tài)的線(xiàn)程 WAITING:正在等待另一個(gè)線(xiàn)程執(zhí)行特定動(dòng)作的線(xiàn)程 TIMED_WAITING:等待另一個(gè)線(xiàn)程執(zhí)行時(shí)間到達(dá)指定時(shí)間 TERMINATED:線(xiàn)程退出執(zhí)行public class TestState { public static void main(String[] args) { Thread thread = new Thread(()->{ for (int i = 0; i < 5; i++) {try { Thread.sleep(1000);} catch (InterruptedException e) { e.printStackTrace();} } System.out.println('/////'); }); //觀察線(xiàn)程狀態(tài) Thread.State state = thread.getState(); System.out.println(state); //New狀態(tài) thread.start(); state = thread.getState(); System.out.println(state);//Run狀態(tài) while (state!=Thread.State.TERMINATED){ try {Thread.sleep(100); } catch (InterruptedException e) {e.printStackTrace(); } state = thread.getState();//更新線(xiàn)程狀態(tài) System.out.println(state);//輸出狀態(tài) } }}
線(xiàn)程禮讓
當(dāng)前正在執(zhí)行的線(xiàn)程暫停,但是不會(huì)阻塞 當(dāng)前線(xiàn)程失去處理機(jī),編程就緒狀態(tài) 禮讓是否成功取決于CPU,如果禮讓成功,則等待下一次調(diào)度public class TestYield { public static void main(String[] args) { MyYield myYield = new MyYield(); new Thread(myYield,'a').start(); new Thread(myYield,'b').start(); }}class MyYield implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+'線(xiàn)程開(kāi)始執(zhí)行'); Thread.yield(); System.out.println(Thread.currentThread().getName()+'線(xiàn)程停止執(zhí)行'); }}
執(zhí)行結(jié)果:
線(xiàn)程強(qiáng)制執(zhí)行到結(jié)束
使用join()方法 使用join()方法的線(xiàn)程會(huì)強(qiáng)制執(zhí)行直到結(jié)束,不會(huì)讓出處理機(jī)public class TestJoin implements Runnable{ @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println('強(qiáng)制執(zhí)行線(xiàn)程來(lái)了'+i); } } public static void main(String[] args) throws Exception{ TestJoin testJoin = new TestJoin(); Thread thread = new Thread(testJoin); thread.start(); for (int i = 0; i < 500; i++) { if(i==200){thread.join(); } System.out.println('主線(xiàn)程'+i); } }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟2. 解決android studio引用遠(yuǎn)程倉(cāng)庫(kù)下載慢(JCenter下載慢)3. ajax請(qǐng)求添加自定義header參數(shù)代碼4. ASP基礎(chǔ)知識(shí)VBScript基本元素講解5. 基于javascript處理二進(jìn)制圖片流過(guò)程詳解6. Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫(kù)7. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)8. 教你如何寫(xiě)出可維護(hù)的JS代碼9. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)10. 使用python 計(jì)算百分位數(shù)實(shí)現(xiàn)數(shù)據(jù)分箱代碼
