Thread和Runnable的區別

1、繼承Thread類

/**
 * 線程類
 * @author
 * @date 2018/7/31 16:04
 */
public class MyThread extends Thread {

    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 8; i++) {
            System.out.println("name=" +name+":"+ i);
        }
    }
}
/**
 * 測試類
 * @author limh
 * @date 2018/7/31 16:07
 */
public class TestMain {

    public static void main(String[] args){

        //新建線程
        MyThread t1 = new MyThread("A");
        MyThread t2 = new MyThread("B");

        //啓動線程
        t1.start();
        t2.start();
    }
}

2、實現Runnable接口

若是一個類繼承Thread,則不適合資源共享。可是若是實現了Runnable接口的話,則很容易的實現資源共享java

/**
 * Runnable類
 * @author
 * @date 2018/7/31 16:15
 */
public class MyThread1 implements Runnable {

    private int ticket = 10;

    @Override
    //公共資源,要在run方法以前加上synchronized,要否則會出現搶資源的狀況
    public synchronized void run() {
        for (int i=0;i<10;i++){
            if (this.ticket > 0){
                System.out.println("賣票:ticket"+this.ticket--);
            }
        }
    }
}
/**
 * 測試類
 * @author limh
 * @date 2018/7/31 16:07
 */
public class TestMain {

    public static void main(String[] args){

        //測試Runnable
        MyThread1 t1 = new MyThread1();

        //同一個t1,資源共享。若是不是同一個,則達不到該效果
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
    }
}

運行結果

3、總結

實現Runnable接口比繼承Thread類所具備的優點:ide

  1. 適合多個相同的程序代碼的線程去處理同一個資源
  2. 能夠避免java中的單繼承的限制
  3. 增長程序的健壯性,代碼能夠被多個線程共享,代碼和數據獨立。
相關文章
相關標籤/搜索