为什么sysout总是打印1?

时间:2016-01-24 12:08:10

标签: java

在下面的代码中,为什么sysout总是打印1?

public class A implements ActionListener{       
    public static int X = 0;
    private Timer timer;        
    public A(){
        timer = new Timer(16 ,this);
        timer.setInitialDelay(16);
        timer.start();      
    }
    public void actionPerformed(ActionEvent arg0) {
        System.out.println(X);
    }           
    public static void main(String args[]){
        new A();
        new B().start();
    }
}    
class B extends Thread{

    public void run(){
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        A.X++;      
    }
}

我期待这样的输出:

1
2
3
...

请注意,我不想使用其他方法。

1 个答案:

答案 0 :(得分:0)

这是因为线程的run方法只被调用一次。如果您想查看预期结果,请尝试以下方法:

class B extends Thread{

public void run(){
      try {
           while(true){ //add here some condition when you want to stop the loop
               A.X++; 
               Thread.sleep(200);
           }
       } catch (InterruptedException e) {
          e.printStackTrace();
      }

   }
}
相关问题