Thread.sleep方法永久停止线程

时间:2012-01-25 10:14:07

标签: 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();
               }
          }
   }

上面的代码试图创建一个竞争条件,但在SelfRunner.run中,对Thread.sleep(250)的调用会停止程序执行,而不会将输出打印到命令行。

当我注释掉那一行时,它运作正常。

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

1 个答案:

答案 0 :(得分:7)

你确实意识到你每50000/4秒只打印一次,对吧?你可能想再等一会儿。 :)