2
class SelfishRunner extends Thread{
private int tick = 1;
private int num ;
public SelfishRunner(int x){
this.num = x;
}
@Override
public void run(){
try{
while(tick < 400000){
Thread.sleep(250);
if((tick%50000) == 0){
System.out.println(" Thread# "+num+","+Thread.currentThread().getName()+", tick "+tick);
}
tick++;
}
}catch(Exception e){
System.out.println(e);
}
}
}
public class RaceDemo{
private final static int NUMRUNNERS = 2;
public static void main(String[] args){
SelfishRunner[] runners = new SelfishRunner[NUMRUNNERS];
for(int x=0,y=1; x < NUMRUNNERS; x++){
runners[x] = new SelfishRunner(x);
runners[x].setPriority(y++);
}
runners[0].setName("JEEPERS");
runners[1].setName("KREEPERS");
for(int x=0; x < NUMRUNNERS; x++){
runners[x].start();
}
}
}
上面的代碼試圖創建一個競爭條件,但在SelfRunner.run
調用Thread.sleep(250)
停止程序執行,而不進行打印輸出到命令行。了Thread.sleep方法停止線程permenantly
當我註釋掉該行時,它可以正常工作。
有人可以告訴我爲什麼嗎?
'Thread.sleep(250)'將使線程睡眠250毫秒(1/4秒)。它將每50,000次迭代打印一次。這意味着在打印內容之前,您必須等待50,000/4 = 12,500秒(3小時28分20秒)。你有這麼多的耐心嗎? – Jesper