/*
* Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved.
*/
package com.huanghe.thread;
/**
* 功能描述
*
* @author h00518386
* @since 2022-01-14
*/
public class TicketConsumer implements Runnable {
private Integer i;
public TicketConsumer(int i) {
super();
this.i = i;
}
@Override
public void run() {
while (true) {
// 1、张三拿到锁,i=7, 3、此时锁对象发送改变,李四也可以进来
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();
}
// 2、张三此时的i = 7, 打印 “ 张三抢到了第7张票 ”
// 3、计算i--,得到 i = 6导致i的hashcode发生改变,锁对象就发生的变化
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();
}
}