課程
/后端開發
/Java
/深入淺出Java多線程
為什么代碼中的第二個類是用接口來寫的呢
2018-08-28
源自:深入淺出Java多線程 2-3
正在回答
繼承Thread和實現Runnable其區別主要在于共享數據,Runnable接口是可以共享數據的,多個Thread可以同時加載一個Runnable,當各自Thread獲得CPU時間片的時候開始運行Runnable,Runnable里面的資源被共享。
而例子中
class?Actress?implements?Runnable{ ????static?int?count?=?0; ????@Override ????public?void?run()?{ ????????System.out.println(Thread.currentThread().getName()?+?"是一個演員!"); ????????boolean?courrent?=?true; ????????while(courrent)?{ ????????????System.out.println(Thread.currentThread().getName()?+?"登臺演出第"?+?(++count)?+?"場次!"); ????????????if(count>=100){ ????????????????courrent?=?false; ????????????} ????????????if(count%10?==?0){ ????????????????try?{ ????????????????????Thread.sleep(100); ????????????????}?catch?(InterruptedException?e)?{ ????????????????????e.printStackTrace(); ????????????????} ????????????} ????????} ????????System.out.println(Thread.currentThread().getName()?+?"演出結束了"); ????} }
與
public?class?Actor?extends?Thread?{ ????static?int?count?=?0; ????public?void?run()?{ ????????System.out.println(getName()?+?"是一個演員!"); ????????boolean?courrent?=?true; ????????while(courrent)?{ ????????????System.out.println(getName()?+?"登臺演出第"?+?(++count)?+?"場次!"); ????????????if(count>=100){ ????????????????courrent?=?false; ????????????} ????????????if(count%10?==?0){ ????????????????try?{ ????????????????????Thread.sleep(1000); ????????????????}?catch?(InterruptedException?e)?{ ????????????????????e.printStackTrace(); ????????????????} ????????????} ????????} ????????System.out.println(getName()?+?"演出結束了"); ????} ????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還是實現Runnable接口我們都可以創建線程。在實際開發中大多數情況下是實現Runnable接口的,因為它可以共享數據。
舉報
帶你一起深入淺出多線程,掌握基礎,展望進階路線
1 回答有關多線程的Runnable接口
1 回答關于使用Thread.yield()進行線程通訊的問題
3 回答關于停止線程用的keeprunning
1 回答wait()的使用
2 回答為啥 軍隊 是 接口呢?
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網安備11010802030151號
購課補貼聯系客服咨詢優惠詳情
慕課網APP您的移動學習伙伴
掃描二維碼關注慕課網微信公眾號
2018-08-28
繼承Thread和實現Runnable其區別主要在于共享數據,Runnable接口是可以共享數據的,多個Thread可以同時加載一個Runnable,當各自Thread獲得CPU時間片的時候開始運行Runnable,Runnable里面的資源被共享。
而例子中
與
主要是說明不管是繼承Thread還是實現Runnable接口我們都可以創建線程。在實際開發中大多數情況下是實現Runnable接口的,因為它可以共享數據。