1. 程式人生 > >多線程——Thread與Runnable的區別

多線程——Thread與Runnable的區別

over 目標 http 繼承 thread test 啟動 個人 spa

首先,從使用形式上,使用Runnable實現多線程更好,因為避免了單繼承問題,但除了這一點之外,Thread和Runnable之間也存在一些聯系。觀察Thread類的定義形式:

public class Threadextends Objectimplements Runnable

原來Thread類是Runnable接口的子類,那麽Thread類也應該覆寫了run()方法。

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}

private void init有this.target = target;

而之前target的定義是: private Runnable target;

可以形成如下的類繼承結構:

技術分享

所以,在多線程的處理上使用的是代理設計模式。除了上面的關系,在實際開發中使用Runnable還有一個特點:使用Runnable實現的多線程的程序類可以更好的描述出數據共享的概念(並不是說Thread不能)。
(目標是產生若幹個線程進行同一數據的處理操作)
範例:使用Thread實現數據操作
class MyThread extends Thread{   //是一個線程的主體類
    private int
ticket=10;//一共10張票 @Override public void run() { for(int x=0;x<20;x++){ if(this.ticket>0){ System.out.println("賣票,ticket="+this.ticket--); } } } } public class ThreadTest { public static void main(String[] args) { new MyThread().start();
new MyThread().start(); new MyThread().start(); } }

此時只是想啟動三個線程進行賣票處理。結果變為了各自賣各自的三張票。沒有實現共享。分析內存關系:是各自自己的

技術分享

改為:
class MyThread extends Thread{   //是一個線程的主體類
    private int ticket=10;//一共10張票

    @Override
    public void run() {
        for(int x=0;x<20;x++){
            if(this.ticket>0){
                System.out.println("賣票,ticket="+this.ticket--);
            }
        }
    }
}
public class ThreadTest {
    public static void main(String[] args) {

        MyThread mt=new MyThread();
        new Thread(mt).start();
        new Thread(mt).start();
        new Thread(mt).start();
               //即new Thread(new MyThread()).start();
    }
}

輸出結果是:只有10張票,是實現了數據共享。但是相當有兩個人都有水,但是這個人非要喝另外一個人的水,並不好。

範例:使用Runnable實現共享

class MyThread implements Runnable{   //是一個線程的主體類
    private int ticket=10;//一共10張票

    @Override
    public void run() {
        for(int x=0;x<20;x++){
            if(this.ticket>0){
                System.out.println("賣票,ticket="+this.ticket--);
            }
        }
    }
}
public class ThreadTest {
    public static void main(String[] args) {
        MyThread mt=new MyThread();
        new Thread(mt).start();
        new Thread(mt).start();
        new Thread(mt).start();
    }
}

這時的MyThread是沒有start方法的,所以是可以使用Thread的start方法的。實現了數據共享。輸出結果也是共同賣10張票。

Runnable能比Thread更好的實現數據共享的功能,但不是能不能的區別。又因為Runnable用的多,所以就能實現好的實現數據共享的。

多線程——Thread與Runnable的區別