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();
}
} 是都应该产生偶数吧,但是为什么会有奇数打印出来呢?
在线等,解决了就加分!!!!
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();
}
} 是都应该产生偶数吧,但是为什么会有奇数打印出来呢?
在线等,解决了就加分!!!!
i++;
i++;
}改成这样吧
i++;
i++;
}改成这样吧这样一样啊
public synchronized void next() {
i++;
i++;
}
如果你有两个线程运行,在第一个next()执行后,getValue()执行前,就容易出现问题
因为线程你是不知道何时运行的。
可以枷锁,象楼上说的加synchronized