Java多线程实现(2)---Thread与Runnable区别

xiaoxiao2021-02-28  22

从使用形式来讲,明显使用Runnable实现多线程要比继承Thread类要好,因为可以避免但继承局限。 首先看一下Thread类的定义:

public class Thread implements Runnable Thread类是Runnable接口的子类,那么Thread类一定覆写了Runnable接口的run()方法 public void run() { if (target != null) { target.run(); } } public Thread(Runnable target) { init(null, target, "Thread-" + nextThreadNum(), 0); }

在多线程的处理上使用的就是代理设计模式。除了以上的关系之外,实际上在开发之中使用Runnable还有一个特点:使用Runnable实现的多线程的程序类可以更好的描述出程序共享的概念(这块需要注意的是这并不是说Thread不能)

使用Thread实现数据共享(模拟实现买三个人同时买十张票)

class MyThread extends Thread { private int ticket = 10 ; // 一共10张票 @Override public void run() { while(this.ticket>0){ System.out.println("剩余票数:"+this.ticket -- ); } } } public class Thread3 { public static void main(String[] args) { new MyThread().start(); new MyThread().start(); new MyThread().start(); } }

此时启动三个线程实现卖票处理。结果变为了卖各自的票。 上图为代码的结果打印。 使用Runnable实现上述的共享

class MyThread implements Runnable { private int ticket = 10 ; // 一共10张票 @Override public void run() { while(this.ticket>0){ System.out.println("剩余票数:"+this.ticket -- ); } } } public class TestDemo { public static void main(String[] args) { MyThread mt = new MyThread() ; new Thread(mt).start(); new Thread(mt).start(); } }

代码运行结果:

综上所述Runnable实现的多线程的程序类可以更好的描述出程序共享的概念

转载请注明原文地址: https://www.6miu.com/read-2629923.html

最新回复(0)