runnable 是接口。
thread 是类,且实现了runnable接口。
thread部分源码
[java] view plain copy
- public class thread
- implements runnable
- {
- private static class caches
- {
- static final concurrentmap subclassaudits = new concurrenthashmap();
- static final referencequeue subclassauditsqueue = new referencequeue();
在使用runnable定义的子类中没有start()方法,只有thread类中才有。
[java] view plain copy
- public interface runnable
- {
- public abstract void run();
- }
thread类,有一个构造方法:public thread(runnable targer)
[java] view plain copy
- 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的子类实例,也就是说可以通过thread类来启动runnable实现的多线程。
在程序开发中只要是多线程肯定永远以实现runnable接口为主。
实现runnable接口相比继承thread类有如下好处:
1、避免继承的局限,一个类可以继承多个接口。
2、适合于资源的共享。
以卖票为例,总共只有10张动车票了,全国3个窗口在卖。
继承thread类的方法
[java] view plain copy
- package multithreading;
- public class mythreadwithextends extends thread {
- private int tickets = 10;
- @override
- public void run() {
- for (int i = 0; i <= 100; i ) {
- if(tickets>0){
- system.out.println(thread.currentthread().getname() "--卖出票:" tickets--);
- }
- }
- }
- 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张。如果真卖票,就有问题了。
- }
- }
运行结果:
thread-0--卖出票:10
thread-2--卖出票:10
thread-1--卖出票:10
thread-2--卖出票:9
thread-0--卖出票:9
thread-2--卖出票:8
thread-1--卖出票:9
thread-2--卖出票:7
thread-0--卖出票:8
thread-2--卖出票:6
thread-2--卖出票:5
thread-2--卖出票:4
thread-1--卖出票:8
thread-2--卖出票:3
thread-0--卖出票:7
thread-2--卖出票:2
thread-2--卖出票:1
thread-1--卖出票:7
thread-0--卖出票:6
thread-1--卖出票:6
thread-0--卖出票:5
thread-0--卖出票:4
thread-1--卖出票:5
thread-0--卖出票:3
thread-1--卖出票:4
thread-1--卖出票:3
thread-1--卖出票:2
thread-0--卖出票:2
thread-1--卖出票:1
thread-0--卖出票:1
每个线程都独立,不共享资源,每个线程都卖出了10张票,总共卖出了30张。如果真卖票,就有问题了。
实现runnable接口方式
[java] view plain copy
- package multithreading;
- public class mythreadwithimplements implements runnable {
- private int tickets = 10;
- @override
- public void run() {
- for (int i = 0; i <= 100; i ) {
- if(tickets>0){
- system.out.println(thread.currentthread().getname() "--卖出票:" tickets--);
- }
- }
- }
- public static void main(string[] args) {
- mythreadwithimplements myrunnable = new mythreadwithimplements();
- thread thread1 = new thread(myrunnable, "窗口一");
- thread thread2 = new thread(myrunnable, "窗口二");
- thread thread3 = new thread(myrunnable, "窗口三");
- thread1.start();
- thread2.start();
- thread3.start();
- }
- }
运行结果:
窗口二--卖出票:10
窗口三--卖出票:9
窗口一--卖出票:8
窗口三--卖出票:6
窗口三--卖出票:4
窗口三--卖出票:3
窗口三--卖出票:2
窗口三--卖出票:1
窗口二--卖出票:7
窗口一--卖出票:5
每个线程共享了对象myrunnable的资源,卖出的总票数是对的,但是顺序是乱的,怎么办?