发射倒计时程序:
/**
* 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();
}
}
}
如何驱动
示例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");
}
}
输出结果:
总结:当从runnable导出一个类时,它必须具有run()方法,但是这个方法并无特殊之处,它不会产生任何内在的线程能力。要实现线程行为,你必须显式地将一个任务附着到线程上。
示例二:
/**
* 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在新起线程中启动该任务。
尽管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");
}
}
输出:每次执行结果不惟一
结论:输出说明不同的任务的执行在线程被换进换出时混在了一起。这种交换是由线程调度器自动控制的。
转载于:https://my.oschina.net/u/560971/blog/1527075