下面的例子能够说明- class A implements Runnable {
- public static void main(String[] args) {
- A a = new A();
- Thread t1 = new Thread(a);
- Thread t2 = new Thread(a);
- Thread t3 = new Thread(a);
- t1.start();
- t2.start();
- t3.start();
- }
- Integer i = 100;
- Integer p = 100;
- //Object o = new Object();
- public void run() {
- while (true)
- {
- synchronized (i) {
- if (p>0)
- {
- try {
- Thread.sleep(20);
- } catch (Exception e) {
- e.printStackTrace();
- }
- //System.out.println(Thread.currentThread().getName()+" == "+i--);
- System.out.println(Thread.currentThread().getName()+" == "+p--);
- }
- }
- }
- }
- }
复制代码 你只要不执行i--就没事.
或者,你可以在同步判断条件上设一个断点,在eclipse里面会很清晰的看到,由于执行了i--也就是相当于i=i-1的语句之后,变量的引用发生了变化 |