1. 程式人生 > 其它 >實現Runnable (推薦使用,不用 實現thread類)

實現Runnable (推薦使用,不用 實現thread類)

建立執行緒方式2: 實現runnable 介面, 重新run方法,丟入runnable介面實現類,呼叫start方法

1  定義 MyRunnable 類 實現Runnable 介面

2實現run方法,編寫執行緒執行體

3建立執行緒物件,呼叫start方法啟動執行緒

 1 public static void main(String [] args){
 2  TestThread test1 = new TestThread();     //建立runnable介面的實現類物件                          3.丟入runnable介面實現類,呼叫start方法
 3   Thread thread = new
Thread(test1); //建立執行緒物件,通過執行緒物件來開啟執行緒,代理 4 thread.start(); 5 //3.4行程式碼 簡寫為: new Thread (test1).start(); 6 for(i=0;i<100;i++){ 7 System.out.println("run"+i); 8 } 9 } 10 public calss TestThread implements
Runnable { //1.定義 MyRunnable 類實現runnable 介面 11 public void run(){ // 2.重新run方法 12 for(i=0;i<20;i++){ 13 System.out.println("run"+i); 14 } 15 16 } 17 }