java多線程:繼承Thread和實現Runable接口的區別


java中我們想要實現多線程常用的有兩種方法,繼承Thread 類和實現Runnable 接口,有經驗的程序員都會選擇實現Runnable接口 ,其主要原因有以下兩點:

首先,java只能單繼承,因此如果是采用繼承Thread的方法,那么在以后進行代碼重構的時候可能會遇到問題,因為你無法繼承別的類了。

其次,如果一個類繼承Thread,則不適合資源共享。但是如果實現了Runable接口的話,則很容易的實現資源共享。

1.繼承Thread——多線程執行各自的資源,線程執行的資源互不干涉,各自執行各自的

public class testThread extends Thread{
    private int count=5;
    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 class main1 {
    public static void main(String[] args) {
        testThread mTh1=new testThread("A");
        testThread mTh2=new testThread("B");
        mTh1.start();
        mTh2.start();
    }
}

 

控制台輸出(線程1和線程2之間的變量是不能共享的,每次count--都有各自的變量和結果。):

 

2.實現Runnable接口——多線程共享同一資源:

public class testRunnable implements Runnable{
    private int count=15;
    @Override
    public void run() {
          for (int i = 0; i < 5; i++) {
              System.out.println(Thread.currentThread().getName() + "運行  count= " + count--);
                try {
                    Thread.sleep((int) Math.random() * 10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    }
    
}
public class main2 {
    public static void main(String[] args) {
        testRunnable mTh = new testRunnable();
            new Thread(mTh, "C").start();//同一個mTh,但是在Thread中就不可以,如果用同一個實例化對象mt,就會出現異常   
            new Thread(mTh, "D").start();
            new Thread(mTh, "E").start();
    }
 
}

 

控制台輸出(三個不同的線程之間的變量是共享的,每次count--得到的記過都是再上一個線程運行結果之上得到的。):

轉自:https://blog.csdn.net/u010926964/article/details/74962673


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM