溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java_6 線程創(chuàng)建的方式

發(fā)布時(shí)間:2020-07-05 14:33:00 來源:網(wǎng)絡(luò) 閱讀:176 作者:小西幾 欄目:編程語言

一、創(chuàng)建線程的方法

1.繼承Thread類

實(shí)現(xiàn)步驟:
(1)創(chuàng)建一個(gè)繼承于Thread類的子類
(2)重寫Thread類的run()方法【線程執(zhí)行的操作聲明在run()中】
(3)創(chuàng)建Thread類的子類的對(duì)象
(4)通過此對(duì)象調(diào)用start()方法【①啟動(dòng)線程②調(diào)用當(dāng)前線程對(duì)象的run方法】
代碼

//(1)創(chuàng)建一個(gè)繼承于Thread類的子類
class MyThread1 extends Thread{
    public MyThread1(String name){
        super(name);
    }
        //(2)重寫Thread類的run()方法
    @Override
    public void run() {
        System.out.println("第一種創(chuàng)建線程");
        }
    }
}
public class ThreadTest{
    public static void main(String[] args) {
        //(3)創(chuàng)建Thread類的子類的對(duì)象
        MyThread1 t1=new MyThread1();
        //(4)通過此對(duì)象調(diào)用start()方法
        t1.start();
        }
}

2.實(shí)現(xiàn)Runnable接口

實(shí)現(xiàn)步驟
(1)創(chuàng)建一個(gè)實(shí)現(xiàn)了Runnable接口的類
(2)該實(shí)現(xiàn)類 去實(shí)現(xiàn)Runnable中的抽象方法run()
(3)創(chuàng)建實(shí)現(xiàn)類的對(duì)象
(4)將此對(duì)象作為參數(shù)傳遞到Thread類的構(gòu)造器中,創(chuàng)建 Thread類的對(duì)象
【Thread構(gòu)造方法源碼:public Thread(Runnable target)】
(5)通過Thread類的對(duì)象調(diào)用start()
代碼

//1.創(chuàng)建一個(gè)實(shí)現(xiàn)了Runnable接口的類
class MyThread2 implements Runnable{
    @Override
    //2.實(shí)現(xiàn)類去實(shí)現(xiàn)Runnable中的抽象方法run()
    public void run() {
        System.out.println("第二種創(chuàng)建線程:實(shí)現(xiàn)Runnable接口");
            }
     }
         public class ThreadTest1 {
    public static void main(String[] args) {
        //3.創(chuàng)建實(shí)現(xiàn)類的對(duì)象
        MyThread2 m=new MyThread2();
        // 4.將此對(duì)象作為參數(shù)傳遞到Thread類的構(gòu)造器中,創(chuàng)建Thread類的對(duì)象
        Thread thread = new Thread(m);
        // 5.通過Thread類的對(duì)象調(diào)用start()
         thread.start();

二、說明

在前邊說過start()方法的作用:
(1)啟動(dòng)線程
(2)調(diào)用當(dāng)前線程的run()方法
那么問題來了:為什么在使用Runnable接口創(chuàng)建線程的方法中,明明是Thread類的對(duì)象調(diào)用的start(),為什么最終會(huì)是實(shí)現(xiàn)Runnable接口的類的run()方法被執(zhí)行,而不是Thread類的run()方法被執(zhí)行?
原因下次再說,要去上課了
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
呼·······,我回來啦!
(1)首先來看一下Thread類的run()方法的源碼:
java_6 線程創(chuàng)建的方式
說明:如果target非空,就執(zhí)行target的run()方法,那么target又是什么?
(2)再來看一下Thread的一個(gè)構(gòu)造方法Thread(Runnable target)
java_6 線程創(chuàng)建的方式
我們發(fā)現(xiàn)target是一個(gè)Runnable類型的變量,該變量會(huì)作為參數(shù)傳入Thread類的構(gòu)造器中。
java_6 線程創(chuàng)建的方式
說明:target就是實(shí)現(xiàn)了Runnable接口的實(shí)現(xiàn)類的實(shí)例對(duì)象。
因?yàn)樵搶?duì)象非空,所以Thread的對(duì)象在調(diào)用了自身的run()方法,然后發(fā)現(xiàn)target對(duì)象非空,因此轉(zhuǎn)而執(zhí)行了實(shí)現(xiàn)類的run()方法。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI