天天看點

java多線程中runnable接口和thread類差別

                      java多線程中實作runnable接口和繼承thread類差別

我們可以通過繼承runnable接口實作多線程,也可以通過繼承thread實作多線程

先來看下兩種實作方式的代碼。

繼承thread類:

package Test;

public class testThread extends Thread{
	private int count=10;
	private String name;
    public testThread(String name) {
       this.name=name;
    }
	public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + "運作  count= " + count--);
            try {
                sleep((int) Math.random() * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
       
	}
	public static void main(String[] args) {
			testThread mTh1=new testThread("A");
			testThread mTh2=new testThread("B");
			mTh1.start();
			mTh2.start();
	}

}
           

實作runnable接口:

package Test;

public class testThread implements Runnable{
	private int count=10;
    @Override
	public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName()+"運作  count= " + count--);
        }
       
	}
	public static void main(String[] args) {
			testThread mTh1=new testThread();
			new Thread(mTh1,"C").start();
			new Thread(mTh1,"D").start();
			
	}

}
           

運作結果:

繼承thread類:

java多線程中runnable接口和thread類差別

實作runnable接口:

java多線程中runnable接口和thread類差別

主要差別:

1:java中不支援多繼承,一旦繼承了Thread類就沒辦法繼承其他類,擴充性不好。而一個類可以實作多個接口,

這樣擴充性比較好。

2:實作runnable接口是線程資源共享的,在一個線程裡聲明的變量,其他線程可見。對于同步操作比較容易。

而繼承Thread是線程資源非共享的。每個線程都有自己的空間,聲明自己的變量。如果想達到同步的目的,

就需要用到同步鎖。