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 { ; boolean flag = true; public MyThread(String string) { this.setName(string); } @Override public void run() { while(flag){ saleTick(); } } public void saleTick() { ){ ticks--; System.out.println(Thread.currentThread().getName()+":"+ticks); }else{ flag = false; } } }
package com.shine.test; /** * 通过实现Runnable的卖票类 * @author ASUS * */ public class MyRunnable implements Runnable { ; boolean flag = true; @Override public void run() { while(flag){ saleTick(); } } public void saleTick() { ){ 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: thread1: thread1: thread1: thread1: thread1: thread1: thread1: thread1: thread1: thread2: thread2: thread2: thread2: thread2: thread2: thread2: thread2: thread2: thread2: thread3: runnable1: runnable1: runnable1: runnable1: runnable1: runnable1: runnable1: runnable1: runnable1: runnable1: thread3: thread3: thread3: thread3: thread3: thread3: thread3: thread3: thread3:
由于系统自身的线程选择问题 全部由runnable1完成了卖票 但总共只卖出了10张 thread的则卖出了30张