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的情况,不知道是怎么回事?

解决方案 »

  1.   

    我也遇到过  但不知道为什么我感觉是跟JAVA代码变成汇编代码后   中断不是中断整个一条JAVA语句 而是在一条汇编语句上中断的
      

  2.   

    public class Test3 {
        public static void main(String[] args) {
            computer3 t = new computer3();
            new Thread(t).run();
            new Thread(t).run();
            new Thread(t).run();
        }
    }class computer3 extends Thread {
        int i = 10;
        public synchronized void print() {
            
            System.out.println(Thread.currentThread().getName() + ":" + i);
            i--;
        }    @Override
        public void run() {
            while(i > 0) {
                 
                 print();        }
        }
    }
    不要用 obj 作为锁 一个String 就够了
      

  3.   

    synchronized (this),不明白楼主那个静态变量obj是干嘛用的。
      

  4.   

    你run方法后面的sleep时间太短了,你这三个线程都是在同时执行的,同时执行run方法,但由于你后面加了句sleep(100);
    所以每个线程会sleep100ms后看i是否还是>0,而这时如果别的线程的i还没执行完print方法中的i--语句,而本线程的sleep时间已经到了之后,那么自然会执行到while()循环里面去,所以是你程序代码问题。
    看看这个代码以及执行结果会方便你了解。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 (this) {
                    print();
      try {
                    sleep(100);
                } catch (Exception e) {
                }
                }           
            }
        }
    }
      

  5.   

      while (i > 0) {
                synchronized (obj) {
    改成
      while (i > 0) {
                synchronized (obj) {
        if(i>0){ // 加上这个if吧,后面别忘了加上}
      

  6.   

    package test;public class Test {
    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; public void print() {
    System.out.println(Thread.currentThread().getName() + ":" + i);
    i--;
    } public void run() {
    synchronized(this){
    while (i > 0) {
    print();
    try {
    sleep(100);
    } catch (Exception e) {
    }
    }
    }
    }
    }这样好像可以了...