Runnable与Thread区别
简述
Runnable是接口,Thread是类且实现Runnable接口
Thread线程是独立的不共享资源
Runnable是资源共享
在使用Runnable定义的子类中没有start()方法,只有Thread类中才有。
Thread类,有一个构造方法:public Thread(Runnable targer)
此构造方法接受Runnable的子类实例,也就是说可以通过Thread类来启动Runnable实现的多线程。
public Thread(Runnable runnable) { daemon = false; stillborn = false; threadLocals = null; inheritableThreadLocals = null; threadStatus = 0; blockerLock = new Object(); init(null, runnable, (new StringBuilder()).append("Thread-").append(nextThreadNum()).toString(), 0L); }
使用情况
在程序开发中只要是多线程肯定永远以实现Runnable接口为主。
实现Runnable接口相比继承Thread类有如下好处:
1、避免继承的局限,一个类可以继承多个接口。
2、适合于资源的共享。
举例
三个网友分别抢10张优惠券
继承Thread
/** * MyThreadWithExtends * * @author Stephen * @time 2020-7-1 17:59:02 */ public class MyThreadWithExtends extends Thread { private int number = 10; @Override public void run() { for (int i = 0; i <= 100; i++) { if (number > 0) { number--;//优惠卷减一 System.out.println(Thread.currentThread().getName() + "顾客抢到手,剩余优惠券:" + number); } } } public static void main(String[] args) { MyThreadWithExtends thread1 = new MyThreadWithExtends(); MyThreadWithExtends thread2 = new MyThreadWithExtends(); MyThreadWithExtends thread3 = new MyThreadWithExtends(); thread1.start(); thread2.start(); thread3.start(); // 每个线程都独立,不共享资源,每个线程都抢了10张,总共抢了30张。如果真抢,就有问题了。 } }
运行结果
/** * MyThreadWithExtends * * @author Stephen * @time 2020-7-1 17:59:59 */ public class MyThreadWithExtends implements Runnable { private int number = 10; @Override public void run() { for (int i = 0; i <= 100; i++) { if (number > 0) { number--;//优惠卷减一 System.out.println(Thread.currentThread().getName() + "顾客抢到手,剩余优惠券:" + number); } } } public static void main(String[] args) { MyThreadWithExtends myClass = new MyThreadWithExtends(); Thread thread1 = new Thread(myClass,"网友1"); Thread thread2 = new Thread(myClass,"网友2"); Thread thread3 = new Thread(myClass,"网友3"); thread1.start(); thread2.start(); thread3.start(); } }
不忘初心