繼承Thread類創建多線程
1 package cn.ftf.thread; 2 /** 3 * 多線程實現方式一 繼承Thread實現多線程,繼承Thread,重寫run方法 4 * @author 房廷飛 5 * 6 */ 7 public class StartThread extends Thread{ //對象繼承Thread 8 public static void main(String[] args) { 9 StartThread st=new StartThread(); //實例化對象 10 st.start(); //通過子對象的start方法啟動多線程 11 12 for(int i=0;i<20;i++) { 13 System.out.println("一邊coding"); 14 } 15 } 16 public void run() { //重寫對象的run方法 17 for(int i=0;i<20;i++) { 18 System.out.println("一邊聽歌"); 19 } 20 } 21 }
實現Runnable接口創建多線程
1 package cn.ftf.thread; 2 /** 3 * 實現多線程方式二 :實現Runnable,重寫run方法 4 * 避免單繼承局限性,方便共享資源 5 * @author 房廷飛 6 * 7 */ 8 public class StartRun implements Runnable{ 9 10 public static void main(String[] args) { 11 /* 12 //實現方法 13 StartRun st=new StartRun(); //創建實現類對象 14 Thread t=new Thread(st); //創建代理類對象 15 t.start(); //啟動 16 */ 17 18 //或簡潔寫,匿名,合三為一 19 new Thread(new StartRun()).start(); 20 21 for(int i=0;i<20;i++) { 22 System.out.println("一邊coding"); 23 } 24 } 25 @Override 26 public void run() { 27 for(int i=0;i<20;i++) { 28 System.out.println("一邊聽歌"); 29 } 30 31 } 32 33 }
實現Runnable接口相對于繼承Thread類來說,適合多個相同線程處理同一個資源(如搶票)的情況,可以避免由Java的單繼承帶來的局限性。
實際應用中,使用實現runnable接口的方式創建多線程的情況要比繼承Thread類更常見