亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

關于接口的使用

為什么代碼中的第二個類是用接口來寫的呢

正在回答

1 回答

繼承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 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

關于接口的使用

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號