1、Runnable是一个接口,当实现该接口时需要复用run方法,在run方法中实现自己的逻辑。
2、Thread是一个类,它其实实现了Runnable方法,也就是说当你通过new 一个Thread得到一个线程实例时,其实就是重写runnable里面的run方法。当你通过实现runnable创建一个线程实例时,你需要将runnable实例传递一个thread,然后通过.start开启线程。
3、Runnable可以线程同步,但是Thread不可以线程同步,例如一共有10张票,你可以开启3个线程同时卖票,如果你通过继承thread创建一个卖票的类,实例化3个线程会各自卖10张票,一共就卖出了30张,当时你通过实现runnable所创建的卖票类,只需要实例化一个对象,将一个对象传递给三个thread,然后开启三个线程,你会发现三个线程一共只会卖10张。
4、以下是卖票的代码
package com.shine.test; /** * 通过继承thread的卖票类 * @author ASUS * */ public class MyThread extends Thread { public int ticks = 10; boolean flag = true; public MyThread(String string) { this.setName(string); } @Override public void run() { while(flag){ saleTick(); } } public void saleTick() { if(ticks > 0){ ticks--; System.out.println(Thread.currentThread().getName()+":"+ticks); }else{ flag = false; } } }
package com.shine.test; /** * 通过实现Runnable的卖票类 * @author ASUS * */ public class MyRunnable implements Runnable { public int ticks = 10; boolean flag = true; @Override public void run() { while(flag){ saleTick(); } } public void saleTick() { if(ticks > 0){ ticks--; System.out.println(Thread.currentThread().getName()+":"+ticks); }else{ flag = false; } } }
package com.shine.test; public class Test { /**测试 * @param args */ public static void main(String[] args) { MyThread myThread1 = new MyThread("thread1"); MyThread myThread2 = new MyThread("thread2"); MyThread myThread3 = new MyThread("thread3"); myThread1.start(); myThread2.start(); myThread3.start(); MyRunnable myRunnable = new MyRunnable(); Thread runnable1 = new Thread(myRunnable); Thread runnable2 = new Thread(myRunnable); Thread runnable3 = new Thread(myRunnable); runnable1.setName("runnable1"); runnable2.setName("runnable2"); runnable3.setName("runnable3"); runnable1.start(); runnable2.start(); runnable3.start(); } }
结果:
thread1:9 thread1:8 thread1:7 thread1:6 thread1:5 thread1:4 thread1:3 thread1:2 thread1:1 thread1:0 thread2:9 thread2:8 thread2:7 thread2:6 thread2:5 thread2:4 thread2:3 thread2:2 thread2:1 thread2:0 thread3:9 runnable1:9 runnable1:8 runnable1:7 runnable1:6 runnable1:5 runnable1:4 runnable1:3 runnable1:2 runnable1:1 runnable1:0 thread3:8 thread3:7 thread3:6 thread3:5 thread3:4 thread3:3 thread3:2 thread3:1 thread3:0
由于系统自身的线程选择问题 全部由runnable1完成了卖票 但总共只卖出了10张 thread的则卖出了30张