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