標籤: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線程基礎之線程狀態轉換