- 自定義線程的創建方式:
- 方式一:
- 自定義一個類繼承Thread.
- 子類重寫run方法,把自定義線程的任務定義在run方法上。
- 創建thread子類的對象,并且調用start方法開啟線程。
- 方式二:
- 自定義一個類去實現Runnable接口。
- 實現了Runnable接口的run方法, 把自定義線程的任務定義在run方法上。
- 創建Runnable實現類的對象。
- 創建Thread對象,并且把Runnable實現類對象作為參數傳遞進去。
- 調用thread對象的start方法開啟線程。
- 疑問1: Runnable實現類對象是線程對象嗎?
- runnable實現類的對象并不是一個線程對象,只不過是實現了Runnable接口的對象而已。
- 疑問2: 為什么要把Runnable實現類的對象作為參數傳遞給thread對象呢?作用是什么?
- 作用: 是把Runnable實現類的對象的run方法作為了任務代碼去執行了。
- 推薦使用: 推薦使用第二種。 因為java是單繼承的。
public class Demo3 implements Runnable{
@Override
public void run() {
for(int i = 0 ; i< 100 ; i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
System.out.println("當前線程對象:"+Thread.currentThread()); // 當前線程對象是: Thread
System.out.println("當前對象:"+ this); //this對象: Demo3的對象
}
public static void main(String[] args) {
//創建Runnable實現類的對象
Demo3 d = new Demo3();
//創建Thread對象,并且把Runnable實現類對象作為參數傳遞進去
Thread t = new Thread(d,"狗娃");
//調用thead對象的start方法開啟線程。
t.start();
//主線程執行的。
for(int i = 0 ; i< 100 ; i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}