public class AlwaysEven {
  private int i;
  public void next() { i++; i++; }
  public int getValue() { return i; }
  public static void main(String[] args) {
    final AlwaysEven ae = new AlwaysEven();
    new Thread("Watcher") {
      public void run() {
        while(true) {
          int val = ae.getValue();
          if(val % 2 != 0) {
            System.out.println(val);
            System.exit(0);
          }
        }
      }
    }.start();
    while(true)
      ae.next();
  }
} 是都应该产生偶数吧,但是为什么会有奇数打印出来呢?
在线等,解决了就加分!!!!

解决方案 »

  1.   

    val % 2 != 0 这个条件不是输出奇数吗?
      

  2.   

    public synchronized void next() {
    i++;
    i++;
    }改成这样吧
      

  3.   

    public synchronized void next() {
    i++;
    i++;
    }改成这样吧这样一样啊
      

  4.   

    val % 2 != 0 这个条件不是输出奇数吗?是输出奇数,但是应该没输出啊
      

  5.   

    这是线程运行时的很容易出错的问题,
    public synchronized void next() {
    i++;
    i++;
    }
    如果你有两个线程运行,在第一个next()执行后,getValue()执行前,就容易出现问题
    因为线程你是不知道何时运行的。
    可以枷锁,象楼上说的加synchronized