示例代碼
//LiftOff.java
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() {
// TODO Auto-generated method stub
while(countDown -- > 0) {
System.out.println(status());
Thread.yield();
}
}
}
// BasicThreads.java
public class BasicThreads {
public static void main(String[] args) {
Thread t = new Thread(new LiftOff());
t.start();
System.out.println("Waiting for LiftOff");
}
}
截圖
解釋
Thread構(gòu)造器只需要一個(gè)Runnable對(duì)象郁稍。調(diào)用Thread對(duì)象的start()方法為該線程執(zhí)行必需的初始化操作碑韵,然后調(diào)用Runnable的run()方法辐怕,以便在這個(gè)新線程中啟動(dòng)該任務(wù)智绸。盡管start()看起來是產(chǎn)生了一個(gè)對(duì)長期運(yùn)行方法的調(diào)用窝稿,但是從輸出中可以看到楣富,start()迅速地返回了,因?yàn)閃aiting for LiftOff消息在倒計(jì)時(shí)完成之前就出現(xiàn)了伴榔。實(shí)際上纹蝴,程序產(chǎn)生的是對(duì)LiftOff.run()的方法調(diào)用,并且這個(gè)方法還沒有完成潮梯,但是因?yàn)長iftOff.run()是由不同的線程執(zhí)行的骗灶,因此你仍舊可以執(zhí)行main()線程中的其他操作(這種能力并不局限于main()線程,任何線程都可以啟動(dòng)另一個(gè)線程)秉馏。因此耙旦,程序會(huì)同時(shí)運(yùn)行兩個(gè)方法,main()和LiftOff.run()是程序中與其他線程“同時(shí)”執(zhí)行的代碼萝究。