Rah*_*ran 2 java multithreading thread-safety
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码试图创建一个竞争条件,但在SelfRunner.run调用Thread.sleep(250)停止程序执行而不打印输出到命令行.
当我注释掉那一行时,它运行正常.
谁能告诉我为什么?