溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

用代碼解析Java線(xiàn)程狀態(tài)變換過(guò)程

發(fā)布時(shí)間:2020-07-18 16:25:08 來(lái)源:億速云 閱讀:125 作者:小豬 欄目:編程語(yǔ)言

小編這次要用代碼解析Java線(xiàn)程狀態(tài)變換過(guò)程,文章內(nèi)容豐富,感興趣的小伙伴可以來(lái)了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

線(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é)果:

用代碼解析Java線(xiàn)程狀態(tài)變換過(guò)程

線(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);
    }
  }
}

看完這篇關(guān)于用代碼解析Java線(xiàn)程狀態(tài)變換過(guò)程的文章,如果覺(jué)得文章內(nèi)容寫(xiě)得不錯(cuò)的話(huà),可以把它分享出去給更多人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI