發射倒計時程序: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"); } }
輸出:每次執行結果不唯一
結論:輸出說明不一樣的任務的執行在線程被換進換出時混在了一塊兒。這種交換是由線程調度器自動控制的。