1、從JDK文檔中可以發現Thread類實際上也是實現了Runnable;

2、用Thread繼承而來的線程,一個線程序對象只能啟動一次,無論調用多少遍start()方法,結果都只有一個線程;
注:sart()方法是使該線程開始執行,java虛擬機調用該線程的run()方法,也可以調用被子類覆蓋寫過的方法。
3、實現Runnable接口比繼承Thread類的好處:①適合多個相同程序代碼的線程去處理同一資源的情況,也能避免由于java
單線程處理帶來的局限,即處理更為靈活。
②有利于程序的健壯性,能實現資源的共享。
第一種方式:繼承Thread類
class MyThread extends Thread{
//線程延遲時間
private int time;
//線程的名字由Thread累自行管理
public MyThread(String name,int time){
//調用Thread類中的構造方法,設置線程的名字
super(name);
this.time=time;
}
public void run(){
for(int i=0;i<10;i++){
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.printMsg();
}
}
public void printMsg(){
System.out.println (Thread.currentThread().getName()+"-->***正在運行***"+this.time+"秒");
}
}
public class Demo {
public static void main(String[] args){
MyThread mt = new MyThread("AA",100);
MyThread mt1 = new MyThread("BB",200);
MyThread mt2 = new MyThread("CC",300);
mt.start();
mt1.start();
mt2.start();
}
}

第二方式:實現Ruanable接口
class MyThread1 implements Runnable{
private String name;
private int time;
public MyThread1(String name,int time){
this.name= name;
this.time=time;
}
public void run(){
for(int i=0;i<10;i++){
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.printMsg();
}
}
public void printMsg(){
System.out.println (this.name+"-->***正在運行***"+this.time+"秒");
}
}
public class DemoF {
public static void main(String[] args){
MyThread mt = new MyThread("AA",100);
MyThread mt1 = new MyThread("BB",200);
MyThread mt2 = new MyThread("CC",300);
mt.start();
mt1.start();
mt2.start();
}
}
運行結果:類同于上一種方法的結果,只是出的順序不相同