3.多线程之Thread VS Runnable

来源:互联网 发布:什么事非农数据 编辑:程序博客网 时间:2024/05/20 16:34

两种方式的比较

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。