Thread和Runnable的區(qū)別

  1. 實(shí)現(xiàn)Runnable接口,可以避免java單繼承機(jī)制帶來(lái)的局限;
  2. 實(shí)現(xiàn)Runnable接口,可以實(shí)現(xiàn)多個(gè)線程共享同一段代碼(數(shù)據(jù));
    ex:

public class ThreadTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        MyThread thread3 = new MyThread();
        thread1.start();
        thread2.start();
        thread3.start();
        
        MyRunnable runnable1 = new MyRunnable("r1");
        
        new Thread(runnable1).run();
        new Thread(runnable1).run();
        new Thread(runnable1).run();
        
    }

}

class MyThread extends Thread
{
    int things = 5;
    @Override
    public void run() {
        while(things > 0)
        {
            System.out.println(currentThread().getName() + " things:" + things);
            things--;
        }
    }
}

class MyRunnable implements Runnable
{
    String name;
    
    public MyRunnable(String name)
    {
        this.name = name;
    }
    
    int things = 5;
    @Override
    public void run() {
        while(things > 0)
        {
            things--;
            System.out.println(name + " things:" + things);
        }
        
    }
}


運(yùn)行結(jié)果:

Thread-2 things:5
r1 things:4
r1 things:3
Thread-1 things:5
Thread-1 things:4
Thread-1 things:3
r1 things:2
Thread-2 things:4
Thread-2 things:3
Thread-2 things:2
Thread-2 things:1
r1 things:1
Thread-1 things:2
r1 things:0
Thread-1 things:1
Thread-0 things:5
Thread-0 things:4
Thread-0 things:3
Thread-0 things:2
Thread-0 things:1

注解:多個(gè)Thread可以同時(shí)加載一個(gè)Runnable,當(dāng)各自Thread獲得CPU時(shí)間片的時(shí)候開始運(yùn)行runnable,runnable里面的資源是被共享的。

  1. 線程池只能放入實(shí)現(xiàn)Runable或Callable類線程,不能直接放入繼承Thread的類。
最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 線程Thread的5狀態(tài):創(chuàng)建——>就緒——>運(yùn)行——>阻塞——>停止創(chuàng)建:new就緒:創(chuàng)建對(duì)象后,執(zhí)行start...
    ShereenAo閱讀 1,243評(píng)論 0 5
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚_t_閱讀 34,687評(píng)論 18 399
  • 因?yàn)殚L(zhǎng)期便秘,前陣子朋友介紹在一家信佛的網(wǎng)店買水果酵素喝,調(diào)理腸胃。 半個(gè)月了,多年便秘才只是稍有改善,但意外發(fā)現(xiàn)...
    止末閱讀 2,689評(píng)論 0 3
  • 語(yǔ)文老師結(jié)束表演的時(shí)候剛好下了課,我把作業(yè)還給林安,順便把紙條還了回去,我還在上面寫了一個(gè)問(wèn)題 “你為什么要向我道...
    柚子寒一閱讀 290評(píng)論 0 0
  • 還有沒(méi)有比人類更喧囂的物種, 不是因?yàn)轲囸I而覓食, 不在安靜里找尋影子, 沒(méi)有奢望小楷寫就的故事, 從樂(lè)園里發(fā)現(xiàn)的...
    百字生閱讀 439評(píng)論 0 6

友情鏈接更多精彩內(nèi)容