徹底理解Runnable和Thread的區別


昨天去面試,面試官問了一個問題:Runnable和Thread有什么區別,因為針對這個問題以前有背過,並且網上大多數都是這些結論,所以脫口而出:

1.Thread有單繼承的問題;
2.Runnable便於實現資源共享,而Thread不能;

然而面試官好像並沒有什么表示。之后結束后我就找了一下度娘,得到了這篇文章:
https://blog.csdn.net/zhaojianting/article/details/97664370

突然發現“Runnable便於實現資源共享”這一優點好像並不合理,以下是我的代碼實現。

使用Thread實現多線程

public class MyThread extends Thread {

    private int ticket = 5;

    @Override
    public void run() {
        while (true) {
            System.out.println("Thread ticket = " + ticket--);
            if (ticket < 0) {
                break;
            }
        }
    }

}

public class Test {
    public static void main(String[] args) {

            //Test Thread

        new MyThread().start();
        new MyThread().start();

    }
}
    
執行結果如下:
Thread ticket = 5
Thread ticket = 4
Thread ticket = 3
Thread ticket = 2
Thread ticket = 1
Thread ticket = 0
Thread ticket = 5
Thread ticket = 4
Thread ticket = 3
Thread ticket = 2
Thread ticket = 1
Thread ticket = 0

並不能實現資源共享,跟以前背的面試題答案一樣;但真的是這樣嗎?我們仔細看一下,代碼中我們創建了兩個MyThread對象,每個對象都有自己的ticket成員變量,當然會多賣1倍。現在我們重新測試一下,請看測試代碼:

public class Test {
    public static void main(String[] args) {

            //Test Thread

        MyThread t1 = new MyThread();
        new Thread(t1).start();
        new Thread(t1).start();
    }
}

測試結果如下:
Thread ticket = 5
Thread ticket = 4
Thread ticket = 3
Thread ticket = 2
Thread ticket = 1
Thread ticket = 0
Thread ticket = -1

可以看到這次我們只創建了一個MyThread對象,並沒出現賣兩倍票的情況,Thread也可以實現資源共享。

因為多線程訪問同一變量會有並發問題(需要加鎖),所以Thread正確的寫法如下:

public class MyThread extends Thread {

    private int ticket = 5;

    @Override
    public void run() {
        if (ticket > 0) {
            synchronized (this) {
                if (ticket > 0) {
                    while (true) {
                        System.out.println("Thread:" + Thread.currentThread().getName() + "--Thread ticket = " + ticket--);
                        if (ticket < 0) {
                            break;
                        }
                    }
                }
            }
        }
    }

}

public class Test {
    public static void main(String[] args) {

            //Test Thread

        MyThread t1 = new MyThread();
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
    }
}

執行結果如下:
Thread:Thread-1--Thread ticket = 5
Thread:Thread-1--Thread ticket = 4
Thread:Thread-1--Thread ticket = 3
Thread:Thread-1--Thread ticket = 2
Thread:Thread-1--Thread ticket = 1
Thread:Thread-1--Thread ticket = 0

現在看Thread和Runnable的源碼:


public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }

    private volatile String name;
    private int            priority;
    private Thread         threadQ;
    private long           eetop;
    
    

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

結論:其實Thread也就是實現了Runnable接口,提供了更多的方法而已。所以說Thread與Runnable並沒有什么區別。如果硬要說有什么區別的話,那就是類與接口的區別,繼承與實現的區別。另外最重要的是,學習的時候不要忘了思考哦!


免責聲明!

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



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