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();
}
} 是都应该产生偶数吧,但是为什么会有奇数打印出来呢?
在线等,解决了就加分!!!!
解决方案 »
- 小妹留学僧~关于java的问题,异国他乡向各位同胞大大求助啊,求助求助!
- 请各位高手帮忙,在下不胜感激
- String和StringBuffer的区别
- Hashmap与Hashtable的区别
- http协议下的大文件断点上传
- 请问java.applet.Applet与javax.swing.JApplet有什么区别?
- purples及各位大侠请再帮忙详解一下代码
- 请问:有没有对数组(int)进行排序的的方法???
- tomcat出事了,谁来帮我看看,分不够了可以加!!!!
- Eclipse导入JAR包无法Import的问题
- 请问如何把一个对象列表(Vector)从applet传递到servlet?
- 线程加锁?
i++;
i++;
}改成这样吧
i++;
i++;
}改成这样吧这样一样啊
public synchronized void next() {
i++;
i++;
}
如果你有两个线程运行,在第一个next()执行后,getValue()执行前,就容易出现问题
因为线程你是不知道何时运行的。
可以枷锁,象楼上说的加synchronized