1 /** 2 * @author zhao 3 * @TIME 0419 22:56 End 4 *定義線程的第二種方法:實現Runnable接口(不考慮安全問題) 5 *步驟:1,定義一個子類實現Runnable接口 6 * 2,在子類中覆蓋run()方法,並且將多線程鎖執行的代碼寫入run方法中 7 * 3,通過Thread類建立線程對象; 8 * 4,將Runnable接口的子類對象作為實際參數傳遞給Thread類的構造函數。 9 為什么要將Runnable接口的子類對象傳遞給Thread的構造函數。 10 因為,自定義的run方法所屬的對象是Runnable接口的子類對象。 11 所以要讓線程去指定指定對象的run方法。就必須明確該run方法所屬對象。 12 頓悟 (結合今天剛看的入門問題: 13 1,在Test項目中java.Iduction.test中,String s ="Hello world";String string =s; 14 注意:s不是一個對象,而是一個String類型的引用,指向對象的地址 15 同理:為什么要將Runnable接口的子類對象傳遞給Thread的構造函數。 16 17 */ 18 //舉例:定義一個賣票程序 19 package ThreadDemoOne; 20 class Ticket implements Runnable //實現接口,注意英語單詞 21 { 22 private int tick =100;//定義票數為100張 23 public void run() 24 { 25 while(true)//true true true 寫錯過兩遍了。while(True)就是執行循環。 26 { 27 if(tick>0) 28 { 29 System.out.println("售票員編號"+Thread.currentThread().getName()+"這是第"+tick+"張票"); 30 tick--; 31 } 32 } 33 } 34 } 35 public class ThreadDemo4 36 { 37 public static void main(String[] args ) 38 { 39 Ticket t=new Ticket();//聲明一個Ticket類型的對象的“引用”,這個引用指向Ticket對象 40 Thread t1=new Thread(t);//創建一個線程,聲明一個Thread類型的t1變量,t1變量又指向了t所指向的變量。 41 Thread t2=new Thread(t); 42 Thread t3=new Thread(t); 43 Thread t4=new Thread(t); 44 /*new Thread(t)中的t不是一個對象,而是一個聲明為Ticket類型的變量,t指向這個對象的地址 45 * 而將t1~t4指向t,t又是指向run方法中的對象,即線程t1~t4指向ticket對象的地址 46 * 如果不指向對象,線程將不知道執行哪個run方法。 47 */ 48 //t1.run();犯錯誤了,注意不能是run方法,應該是start方法 49 t1.start(); 50 t2.start(); 51 t3.start(); 52 t4.start(); 53 54 55 56 } 57 }