但是在使用Runnable定義的子類中沒有start()方法,只有Thread類中才有。此時觀察Thread類,有一個構造方法:public Thread(Runnable targer)
此構造方法接受Runnable的子類執行個體,也就是說可以通過Thread類來啟動Runnable實現的多
線程。(start()可以協調系統的資源):
package org.runnable.demo;
import org.runnable.demo.MyThread;
public class ThreadDemo01 {
public static void main(String[] args) {
MyThread mt1=new MyThread("線程a");
MyThread mt2=new MyThread("線程b");
new Thread(mt1).start();
new Thread(mt2).start();
}
}
· 兩種實現方式的區別和聯絡:
在程式開發中只要是多線程肯定永遠以實現Runnable介面為主,因為實現Runnable介面相比
繼承Thread類有如下好處:
->避免點繼承的局限,一個類可以繼承多個介面。
->適合於資源的共用
以賣票程式為例,通過Thread類完成:
package org.demo.dff;
class MyThread extends Thread{
private int ticket=10;
public void run(){
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println("賣票:ticket"+this.ticket--);
}
}
}
};
下面通過三個線程對象,同時賣票:
package org.demo.dff;
public class ThreadTicket {
public static void main(String[] args) {
MyThread mt1=new MyThread();
MyThread mt2=new MyThread();
MyThread mt3=new MyThread();
mt1.start();//每個線程都各賣了10張,共賣了30張票
mt2.start();//但實際只有10張票,每個線程都賣自己的票
mt3.start();//沒有達到資源共用
}
}
如果用Runnable就可以實現資源共用,下面看例子:
package org.demo.runnable;
class MyThread implements Runnable{
private int ticket=10;
public void run(){
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println("賣票:ticket"+this.ticket--);
}
}
}
}
package org.demo.runnable;
public class RunnableTicket {
public static void main(String[] args) {
MyThread mt=new MyThread();
new Thread(mt).start();//同一個mt,但是在Thread中就不可以,如果用同一
new Thread(mt).start();//個執行個體化對象mt,就會出現異常
new Thread(mt).start();
}
};
雖然現在程式中有三個線程,但是一共賣了10張票,也就是說使用Runnable實現多線程可以達到資源共用目的。
Runnable介面和Thread之間的聯絡:
public class Thread extends Object implements Runnable
發現Thread類也是Runnable介面的子類。
引用自:http://java.chinaitlab.com/line/820728_2.html