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

全國(guó)咨詢/投訴熱線:400-618-4000

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

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

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

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

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

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

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

    }
}

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

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

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

0 分享到:
和我們?cè)诰€交談!