您好,登錄后才能下訂單哦!
小編這次要用代碼解析Java線(xiàn)程狀態(tài)變換過(guò)程,文章內(nèi)容豐富,感興趣的小伙伴可以來(lái)了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
線(xiàn)程狀態(tài)
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)程禮讓
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é)束
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); } } }
看完這篇關(guān)于用代碼解析Java線(xiàn)程狀態(tài)變換過(guò)程的文章,如果覺(jué)得文章內(nèi)容寫(xiě)得不錯(cuò)的話(huà),可以把它分享出去給更多人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。