the following example : synchronized Integer is invalid

68 views Asked by At

myCode is following:

I want to know why zhangsan and lisi are both can print : 李四9锁对象:1522503870 张三9锁对象:1522503870

public class TicketConsumer implements Runnable {
    private Integer i;

    public TicketConsumer(int i) {
        super();
        this.i = i;
    }

    @Override
    public void run() {
        while (true) {
           
            System.out.println(Thread.currentThread().getName() + i + "锁对象before:" + System.identityHashCode(i));
            
            synchronized (i) {
                System.out.println(Thread.currentThread().getName() + i + "锁对象:" + System.identityHashCode(i));
                if (i > 0) {
                    try {
                        Thread.sleep(100);    // 模拟抢票延迟
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "抢到了第" + i-- + "张票");
                } else {
                    return;
                }
            }
        }
    }

    public static void main(String[] args) {
        TicketConsumer ticket = new TicketConsumer(new Integer(10));
        Thread t1 = new Thread(ticket, "张三");
        Thread t2 = new Thread(ticket, "李四");
        t1.start();
        t2.start();
    }
}

the result is :

张三10锁对象before:1417180225
李四10锁对象before:1417180225
张三10锁对象:1417180225
张三抢到了第10张票
张三9锁对象before:1522503870
李四9锁对象:1522503870
张三9锁对象:1522503870
李四抢到了第9张票
李四8锁对象before:2045992545
李四8锁对象:2045992545
张三抢到了第9张票

I want to know why 张三 and 李四 both can get: 李四9锁对象:1522503870 张三9锁对象:1522503870

1

There are 1 answers

4
rikyeah On

I might be wrong, but when you do i--, you can see that System.identityHashCode(i) changes, so another thread that was waiting outside the synchronized block can now enter it. Synchronizing on objects that change identity/reference is not a good idea, try synchronizing on a Stack and debug with stack.push(...): that will not change reference.