Thread和Runnable实现多线程的区别

用一个购票的例子说明Thread和Runnable实现多线程的区别:

一、Thread实现:

public class Main {

    public static void main(String[] args) {
        new Mythread().start();
        new Mythread().start();
    }

    static class Mythread extends Thread{
        private int tickets=5;

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

运行结果:

 ticks=:5
 ticks=:5
 ticks=:4
 ticks=:4
 ticks=:3
 ticks=:3
 ticks=:2
 ticks=:1
 ticks=:2
 ticks=:1


二、Runnable实现:

public class Main {

    public static void main(String[] args) {
        Mythread mythread=new Mythread();
        new Thread(mythread).start();
        new Thread(mythread).start();
    }

    static class Mythread implements Runnable{
        private int tickets=5;

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

运行结果:

 ticks=:5
 ticks=:4
 ticks=:3
 ticks=:2
 ticks=:1

三、总结:继承Thread类实现的Mythread多线程类不能实现资源共享,原因很明显,每new一个Mythread类里面的ticks都是不同的(每一个Thread为一个线程)。而实现Runnable接口的Mythread类是以同一个对象为核心启动多线程的,同一对象里面的ticks自然是相同的,只是不同线程运行不同的run()方法。

猜你喜欢

转载自blog.csdn.net/lovecaicaiforever/article/details/82497971