並發編程——java線程基礎之線程狀態轉換

來源:互聯網
上載者:User

標籤:pos   輸入   blog   stat   com   進入   inf   需要   區別   

線程的基本概念

線程,有時被稱為輕量級進程(Lightweight Process,LWP),是程式執行流的最小單元。一個標準的線程由線程ID,當前指令指標(PC),寄存器集合和堆棧組成。

——百度百科

線程的轉換狀態

 

線程的建立

  線程的建立有兩種方法,一種是implements自Runnable介面,一種是擴充自Thread類,兩者均需要實現run方法。當線程對象被new出來時,線程進入到初始狀態,當線程執行了start方法時,線程進入到可運行狀態(很短,很快進入到執行狀態)。

Runnable介面
 1 package base.newthread; 2  3 public class Thread2 extends Thread { 4  5     @Override 6     public void run() { 7         System.out.println(Thread.currentThread().getName()); 8     } 9     10 }
Thread類
 1 package base.newthread; 2  3 public class Main { 4     public static void main(String[] args) { 5          6         Thread1 runnable1 = new Thread1();  7         Thread t1 = new Thread(runnable1, "t1");//線程進入初始狀態 8         t1.start(); //線程進入到就緒狀態 9         10         Thread2 t2 = new Thread2(); //線程進入初始狀態11         t2.setName("t2");12         t2.start(); //線程進入到就緒狀態13     }14 }
線程的建立線程的讓出

  進程在執行狀態時,時間片被用完或主動執行了yield方法,則該進程會釋放執行態資源進入到可運行狀態等待被重新調度。下面的例子大體可以看出調用yield與不調用yield方法的區別。

 1 package base.yield; 2  3 public class Thread1 implements Runnable{ 4  5     @Override 6     public void run() { 7         for (int i = 0; i < 100; i++) { 8             System.out.println(Thread.currentThread().getName() + ":" + i); 9             //Thread.yield();10         }11     }12 }
Runnable介面
 1 package base.yield; 2  3 public class Thread2 extends Thread { 4  5     @Override 6     public void run() { 7         for (int i = 0; i < 100; i++) { 8             System.out.println(Thread.currentThread().getName() + ":" + i); 9             //Thread.yield();10         }11     }12     13 }
Thread類
 1 package base.yield; 2  3 public class Main { 4     public static void main(String[] args) { 5          6         Thread1 runnable1 = new Thread1();  7         Thread t1 = new Thread(runnable1, "t1");//線程進入初始狀態 8         t1.start(); //線程進入到就緒狀態 9         10         Thread2 t2 = new Thread2(); //線程進入初始狀態11         t2.setName("t2");12         t2.start(); //線程進入到就緒狀態13     }14 }
用戶端類線程的阻塞

線程進入阻塞有三種分類:

  • 調用synchronize進入到鎖池狀態,當線程擷取到鎖資源則進入到runnable狀態
  • 通過調用wait進入到等待隊列,待其他進程調用了notify或notifyAll後進入到鎖池狀態,當線程擷取到鎖資源則進入到runnable狀態
  • 通過調用sleep、調用join或是阻塞在等待輸入,則進入到阻塞狀態;當sleep時間到達或等待的進程執行結束或擷取到輸入結果後,線程進入到runnable狀態。

 

並發編程——java線程基礎之線程狀態轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.