3.多线程之Thread VS Runnable

两种方式的比较

Runnable方式可以避免Thread方式由于Java单继承特性带来的缺陷。
Runnable可以被多个线程(Thread实例)共享,适用于多个线程处理统一资源资源

分别使用Runnable和Thread模拟火车站卖票

使用Thread方式

/**
 * 一个共五张火车票,三个窗口卖
 * /
class MyThread extends Thread {
    private int count = 5;
    private String name;

    @Override
    public void run() {
        while (count > 0) {
            count--;
            System.out.println(name + "卖出一张票还剩" + count + "张");
        }
    }

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

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

        MyThread myThread1 = new MyThread("窗口1");
        MyThread myThread2 = new MyThread("窗口2");
        MyThread myThread3 = new MyThread("窗口3");

        myThread1.start();
        myThread2.start();
        myThread3.start();
    }
}

样例输出:
窗口1卖出一张票还剩4张
窗口1卖出一张票还剩3张
窗口1卖出一张票还剩2张
窗口1卖出一张票还剩1张
窗口3卖出一张票还剩4张
窗口3卖出一张票还剩3张
窗口3卖出一张票还剩2张
窗口2卖出一张票还剩4张
窗口2卖出一张票还剩3张
窗口2卖出一张票还剩2张
窗口2卖出一张票还剩1张
窗口2卖出一张票还剩0张
窗口3卖出一张票还剩1张
窗口1卖出一张票还剩0张
窗口3卖出一张票还剩0张

使用Runnable方式

/**
 * 一个共五张火车票,三个窗口卖
 * /
class MyRunnable implements Runnable {
    private int count = 5;

    @Override
    public void run() {
        while (count > 0) {
            count--;
            System.out.println(Thread.currentThread().getName() + "卖出一张票还剩" + count + "张");
        }
    }

}

public class RunnableTicket {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();

        Thread myThread1 = new Thread(myRunnable, "窗口1");
        Thread myThread2 = new Thread(myRunnable, "窗口2");
        Thread myThread3 = new Thread(myRunnable, "窗口3");

        myThread1.start();
        myThread2.start();
        myThread3.start();
    }
}

样例输出
窗口3卖出一张票还剩2张
窗口3卖出一张票还剩1张
窗口3卖出一张票还剩0张
窗口2卖出一张票还剩2张
窗口1卖出一张票还剩2张

大家体会一下吧

使用Thread方式时,new三个Thread对象,每个对象都有自己count,使用Runnable方式时,由于时通过同一个Runnable实现类对象new三个Thread对象,他们共用一个count。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章