Skip to content

Instantly share code, notes, and snippets.

@HabaCo
Created June 23, 2014 12:07
Show Gist options
  • Save HabaCo/4b3efb3c142a90ff1b43 to your computer and use it in GitHub Desktop.
Save HabaCo/4b3efb3c142a90ff1b43 to your computer and use it in GitHub Desktop.
Thread 執行緒並行
public class Horse implements Runnable{
static int rankh=1; // 利用 static 使其他 Horse 共用此變數(名次)
int runSpeed; // 跑速不大於 5
int sleepTime; // 休息不大於 1 秒
int totalSleepTime =0; // 總共是睡了多久啊
int range=0; // 起跑點
int end = 500; // 終點
String horseName;
public Horse(String name){
horseName = name;
}
public void run() {
while (range<end){
runSpeed = (int)(Math.random()*6); // 跑速 (0<=x<6 -> 0~5)
sleepTime = (int)(Math.random()*1001); // 打盹的時間 (0<=x<1001 -> 0~1000)
totalSleepTime+=sleepTime; // 目前為止睡了多久
try {
Thread.sleep(sleepTime); // 小睡片刻
} catch (InterruptedException e) {}
range+=runSpeed; // 跑了多遠啊
System.out.println(horseName + " 已經跑了 " + (range>500?500:range) + " 公尺了 !!"); // 賽跑情形
}
System.out.println("第 " + rankh++ + " 名為 " + horseName + " ,一共休息了 " + totalSleepTime + "秒.");
}
}
public class HorseRun {
public static void main(String[] args) {
// 5 匹馬要出發了,請下注
new Thread(new Horse("烈火")).start();
new Thread(new Horse("火箭")).start();
new Thread(new Horse("子彈")).start();
new Thread(new Horse("追風")).start();
new Thread(new Horse("迅雷")).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment