線程,有時被稱爲輕量級進程(Lightweight Process,LWP),是程序執行流的最小單元。一個標準的線程由線程ID,當前指令指針(PC),寄存器集合和堆棧組成。ide
——百度百科spa
線程的建立有兩種方法,一種是implements自Runnable接口,一種是擴展自Thread類,二者均須要實現run方法。當線程對象被new出來時,線程進入到初始狀態,當線程執行了start方法時,線程進入到可運行狀態(很短,很快進入到執行狀態)。線程
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 }
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 }
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 }
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 }
線程進入阻塞有三種分類:code