課程
/后端開發(fā)
/Java
/深入淺出Java多線程
為什么代碼中的第二個(gè)類是用接口來寫的呢
2018-08-28
源自:深入淺出Java多線程 2-3
正在回答
繼承Thread和實(shí)現(xiàn)Runnable其區(qū)別主要在于共享數(shù)據(jù),Runnable接口是可以共享數(shù)據(jù)的,多個(gè)Thread可以同時(shí)加載一個(gè)Runnable,當(dāng)各自Thread獲得CPU時(shí)間片的時(shí)候開始運(yùn)行Runnable,Runnable里面的資源被共享。
而例子中
class?Actress?implements?Runnable{ ????static?int?count?=?0; ????@Override ????public?void?run()?{ ????????System.out.println(Thread.currentThread().getName()?+?"是一個(gè)演員!"); ????????boolean?courrent?=?true; ????????while(courrent)?{ ????????????System.out.println(Thread.currentThread().getName()?+?"登臺(tái)演出第"?+?(++count)?+?"場(chǎng)次!"); ????????????if(count>=100){ ????????????????courrent?=?false; ????????????} ????????????if(count%10?==?0){ ????????????????try?{ ????????????????????Thread.sleep(100); ????????????????}?catch?(InterruptedException?e)?{ ????????????????????e.printStackTrace(); ????????????????} ????????????} ????????} ????????System.out.println(Thread.currentThread().getName()?+?"演出結(jié)束了"); ????} }
與
public?class?Actor?extends?Thread?{ ????static?int?count?=?0; ????public?void?run()?{ ????????System.out.println(getName()?+?"是一個(gè)演員!"); ????????boolean?courrent?=?true; ????????while(courrent)?{ ????????????System.out.println(getName()?+?"登臺(tái)演出第"?+?(++count)?+?"場(chǎng)次!"); ????????????if(count>=100){ ????????????????courrent?=?false; ????????????} ????????????if(count%10?==?0){ ????????????????try?{ ????????????????????Thread.sleep(1000); ????????????????}?catch?(InterruptedException?e)?{ ????????????????????e.printStackTrace(); ????????????????} ????????????} ????????} ????????System.out.println(getName()?+?"演出結(jié)束了"); ????} ????public?static?void?main(String[]?args)?{ ????????Thread?actorThread?=?new?Actor(); ????????actorThread.setName("Mr.Thread"); ????????actorThread.start(); ????????Thread?actress?=?new?Thread(new?Actress(),"Ms.Runnable"); ????????actress.start(); ????} }
主要是說明不管是繼承Thread還是實(shí)現(xiàn)Runnable接口我們都可以創(chuàng)建線程。在實(shí)際開發(fā)中大多數(shù)情況下是實(shí)現(xiàn)Runnable接口的,因?yàn)樗梢怨蚕頂?shù)據(jù)。
舉報(bào)
帶你一起深入淺出多線程,掌握基礎(chǔ),展望進(jìn)階路線
1 回答有關(guān)多線程的Runnable接口
1 回答關(guān)于使用Thread.yield()進(jìn)行線程通訊的問題
3 回答關(guān)于停止線程用的keeprunning
1 回答wait()的使用
3 回答關(guān)于wait()和notify()用法
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號(hào)-11 京公網(wǎng)安備11010802030151號(hào)
購(gòu)課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動(dòng)學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號(hào)
2018-08-28
繼承Thread和實(shí)現(xiàn)Runnable其區(qū)別主要在于共享數(shù)據(jù),Runnable接口是可以共享數(shù)據(jù)的,多個(gè)Thread可以同時(shí)加載一個(gè)Runnable,當(dāng)各自Thread獲得CPU時(shí)間片的時(shí)候開始運(yùn)行Runnable,Runnable里面的資源被共享。
而例子中
與
主要是說明不管是繼承Thread還是實(shí)現(xiàn)Runnable接口我們都可以創(chuàng)建線程。在實(shí)際開發(fā)中大多數(shù)情況下是實(shí)現(xiàn)Runnable接口的,因?yàn)樗梢怨蚕頂?shù)據(jù)。