- Java code
public class Test3 { public static void main(String[] args) { computer3 t = new computer3(); new Thread(t).start(); new Thread(t).start(); new Thread(t).start(); }}class computer3 extends Thread { int i = 10; static Object obj = new Object(); public void print() { System.out.println(Thread.currentThread().getName() + ":" + i); i--; } public void run() { while (i > 0) { synchronized (obj) { print(); } try { sleep(100); } catch (Exception e) { } } }}
程序如上,问题是,正常情况i只会显示到1的,但是多运行几次,会出现i为0,甚至是-1的情况,不知道是怎么回事?
------解决方案--------------------
while (i > 0) {
synchronized (obj) {
改成
- Java code
while (i > 0) { synchronized (obj) { if(i>0){ // 加上这个if吧,后面别忘了加上}