java中二種方法實現一個線程

有兩種方法,一種是繼承Thread類,另一種是實現Runable接口
(1)
public class Test{
 public static void main(String [] args){
  MyThread mt=new MyThread();
  mt.start();
  }
}
class MyThread extends Thread{//繼承Thread類
  int count=0;
  public void run(){//重寫run()方法
  while(true){
  System.out.println("MyThread is running !"+count+"times");
  try{
  sleep(1000);//每隔1m輸出
  count++;
  }catch(InterruptedException e){//撲捉可能產生的中斷異常(非運行時異常)
  System.out.println("產生中斷異常");
  }
if(count==10)return;
  }
  }

(2)  
public class Test{
 public static void main(String [] args){
  RunableDemo rd=new RunableDemo();
  Thread t=new Thread(rd);
  t.start();
  }
}
 class RunableDemo implements Runable{//實現Runable接口
  int count=0;
  public void run(){//重寫run()方法
  while(true){
  System.out.println("MyThread is running !"+count+"times");
  try{
  Thread.sleep(1000);//靜態方法,可以用類名直接調用
  count++;
  }catch(InterruptedException e){//撲捉可能產生的中斷異常
  System.out.println("產生中斷異常");
  }
  if(count==10)return;
  }
  }



}

發佈了106 篇原創文章 · 獲贊 4 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章