发射倒计时程序:ide
/** * Created by Administrator on 2017/8/31. */ public class LiftOff implements Runnable { protected int countDown = 10; private static int taskCount = 0; private final int id = taskCount++; public LiftOff() { } public LiftOff(int countDown) { this.countDown = countDown; } public String status() { return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff!") + ")"; } @Override public void run() { while (countDown-- > 0) { System.out.print(status()); Thread.yield(); } } }
如何驱动this
示例1:线程
在下面的示例中,这个任务的run()不是由单独的线程驱动的,它是在main()中直接调用的对象
/** * Created by Administrator on 2017/8/31. */ public class MainThread { public static void main(String[] args) { LiftOff launch = new LiftOff(); launch.run(); System.out.println("等待发射\r\n"); } }
输出结果:class
总结:当从runnable导出一个类时,它必须具备run()方法,可是这个方法并没有特殊之处,它不会产生任何内在的线程能力。要实现线程行为,你必须显式地将一个任务附着到线程上。yield
示例二:程序
/** * Created by Administrator on 2017/8/31. */ public class MainThread { public static void main(String[] args) { /* LiftOff launch = new LiftOff(); launch.run(); System.out.println("\r\n等待发射\r\n");*/ Thread t = new Thread(new LiftOff()); t.start(); System.out.println("等待发射!"); } }
输出结果:方法
总结:将Runnable对象转变为工做任务的传统方式是把它提交给一个Thread构造器,start()起新线程,run在新起线程中启动该任务。im
尽管start()看起来是产生了一个对长期运行方法的调用,可是从输出中能够看到,start()迅速地返回了,由于“等待发射!"消息在倒计时完成以前就出现了。实际上,你产生的是对LiftOff.run()的方法调用,而且这个方法尚未完成,可是由于LiftOff.run()是由不一样的线程执行的,所以你仍旧能够执行main()线程中的其余操做,因些程序会同时运行2个方法,main()和LiftOff.run()是程序中与其余线程”同时“执行的代码。总结
示例三:
添加更多的线程
/** * Created by Administrator on 2017/8/31. */ public class MainThread { public static void main(String[] args) { for (int i = 0; i < 5; i++) { new Thread(new LiftOff()).start(); } System.out.print("等待发射\r\n"); } }
输出:每次执行结果不唯一
结论:输出说明不一样的任务的执行在线程被换进换出时混在了一块儿。这种交换是由线程调度器自动控制的。