- 自定義線程的創(chuàng)建方式:
- 方式一:
- 自定義一個(gè)類(lèi)繼承Thread.
- 子類(lèi)重寫(xiě)run方法,把自定義線程的任務(wù)定義在run方法上。
- 創(chuàng)建thread子類(lèi)的對(duì)象,并且調(diào)用start方法開(kāi)啟線程。
- 方式二:
- 自定義一個(gè)類(lèi)去實(shí)現(xiàn)Runnable接口。
- 實(shí)現(xiàn)了Runnable接口的run方法, 把自定義線程的任務(wù)定義在run方法上。
- 創(chuàng)建Runnable實(shí)現(xiàn)類(lèi)的對(duì)象。
- 創(chuàng)建Thread對(duì)象,并且把Runnable實(shí)現(xiàn)類(lèi)對(duì)象作為參數(shù)傳遞進(jìn)去。
- 調(diào)用thread對(duì)象的start方法開(kāi)啟線程。
- 疑問(wèn)1: Runnable實(shí)現(xiàn)類(lèi)對(duì)象是線程對(duì)象嗎?
- runnable實(shí)現(xiàn)類(lèi)的對(duì)象并不是一個(gè)線程對(duì)象,只不過(guò)是實(shí)現(xiàn)了Runnable接口的對(duì)象而已。
- 疑問(wèn)2: 為什么要把Runnable實(shí)現(xiàn)類(lèi)的對(duì)象作為參數(shù)傳遞給thread對(duì)象呢?作用是什么?
- 作用: 是把Runnable實(shí)現(xiàn)類(lèi)的對(duì)象的run方法作為了任務(wù)代碼去執(zhí)行了。
- 推薦使用: 推薦使用第二種。 因?yàn)閖ava是單繼承的。
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("當(dāng)前線程對(duì)象:"+Thread.currentThread()); // 當(dāng)前線程對(duì)象是: Thread
System.out.println("當(dāng)前對(duì)象:"+ this); //this對(duì)象: Demo3的對(duì)象
}
public static void main(String[] args) {
//創(chuàng)建Runnable實(shí)現(xiàn)類(lèi)的對(duì)象
Demo3 d = new Demo3();
//創(chuàng)建Thread對(duì)象,并且把Runnable實(shí)現(xiàn)類(lèi)對(duì)象作為參數(shù)傳遞進(jìn)去
Thread t = new Thread(d,"狗娃");
//調(diào)用thead對(duì)象的start方法開(kāi)啟線程。
t.start();
//主線程執(zhí)行的。
for(int i = 0 ; i< 100 ; i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。