教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

實現(xiàn)Runnable接口創(chuàng)建多線程

更新時間:2022年03月18日17時17分 來源:傳智教育 瀏覽次數(shù):

  在之前的Java培訓中,我們講到了Thread類,通過繼承Thread類實現(xiàn)可以實現(xiàn)多線程,但是這種方式有一定的局限性。因為Java只支持單繼承,一個類一旦繼承了某個父類就無法再繼承Thread類,例如學生類Student繼承了Person類,就無法通過繼承Thread類創(chuàng)建線程。

  為了克服這種弊端,Thread類提供了另外一個構(gòu)造方法Thread(Runnable target),其中Runnable是一個接口,它只有一個run()方法。當通過Thread(Runnable target)構(gòu)造方法創(chuàng)建線程對象時,只需要為該方法傳遞一行代碼,而不需要調(diào)用Thread類中的run()方法。

  下面通過一個案例來演示如何通過實現(xiàn)Runnable接口的方式來創(chuàng)建多線程,代碼如下文件8-3所示。

  文件8-3的運行結(jié)果如圖8-6所示。

public class Example03 {
    public static void main (String[] args) {
        MyThread myThread = new MyThread () ; // 創(chuàng)建MyThread的實例對象
        Thread thread = new Thread (myThread) ; // 創(chuàng)建線程對象
        thread.start () ;    // 開啟線程,執(zhí)行線程中的run()方法
        while (true) {
            System.out.println("main () 方法在運行");
        }
    }
}
class MyThread implements Runnable {
    public void run () {     // 線程的代碼段,當調(diào)用start()方法時,線程從此處開始執(zhí)行
        while (true) {
            System.out.println("MyThread類的run()方法在運行") ;
        }

    }
}

  文件8-3中,第11~17行代碼定義的MyThread類實現(xiàn)了Runnable接口,并在第12~16行代碼中重寫了Runnable接口中的run()方法;第4行代碼中通過Thread類的構(gòu)造方法將MyThread類的實例對象作為參數(shù)轉(zhuǎn)入,第5行代碼中使用start()方法開啟MyThread線程,最后在第6~8行代碼中定義了一個while死循環(huán)。從圖8-6的運行結(jié)果可以看出,main()方法和run()方法中的打印語句都執(zhí)行了,說明文件8-3實現(xiàn)了多線程。

實現(xiàn)Runnable接口創(chuàng)建多線程

  圖8-6 文件8-3的運行結(jié)果

0 分享到:
和我們在線交談!