步驟:
1. 定義類實現Runnable接口。
2. 覆蓋接口中的run方法。將線程任務代碼定義到run方法中。
3. 創建Thread類的對象。
4. 將Runnable接口的子類對象作為參數傳遞給Thread類的構造函數。
5. 調用Thread類的start方法開啟線程。
實例:
class Demo implements Runnable{ private String name; public Demo(String name) { this.name = name; } public void run() { for (int i = 0; i < 20; i++) { System.out.println(name + ".." + Thread.currentThread().getName() + ".." + i); } } } public class ThreadDemo2 { public static void main(String[] args) { Demo d = new Demo("Demo"); Thread t = new Thread(d); Thread t2 = new Thread(d); t.start(); t2.start(); System.out.println(Thread.currentThread() .getName() + "***");//主線程一開始就執行了一次,然后就不執行了。 } }
這種方式的好處:
1. 實現Runnable接口避免了單繼承的局限性,所以較為常用。
2. 實現Runnable接口的方式,更加的符合面向對象,線程分為兩部分,一部分線程對象,一部分線程任務。
繼承Thread類:run方法在Thread里。線程對象和線程任務耦合在一起。一旦創建Thread類的子類對象,既是線程對象,又有線程任務。
實現Runnable接口:run方法在Runnable里。將線程任務單獨分離出來封裝成對象(Runnable接口類型),用Runnable來標明線程任務,用Thread來明確線程對象。Runnable接口對線程對象和線程任務進行解耦。