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)的调用会暂停程序执行,而无需在命令行上输出输出。

当我注释掉该行时,它可以正常工作。

有人可以告诉我为什么吗?

最佳答案

您确实意识到您只每隔50000/4秒打印一次,对吗?您可能要等待更长的时间。 :)

10-07 19:32