1. /*
    2. * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved.
    3. */
    4. package com.huanghe.thread;
    5. /**
    6. * 功能描述
    7. *
    8. * @author h00518386
    9. * @since 2022-01-14
    10. */
    11. public class TicketConsumer implements Runnable {
    12. private Integer i;
    13. public TicketConsumer(int i) {
    14. super();
    15. this.i = i;
    16. }
    17. @Override
    18. public void run() {
    19. while (true) {
    20. // 1、张三拿到锁,i=7, 3、此时锁对象发送改变,李四也可以进来
    21. System.out.println(Thread.currentThread().getName() + i + "锁对象before:" + System.identityHashCode(i));
    22. synchronized (i) {
    23. System.out.println(Thread.currentThread().getName() + i + "锁对象:" + System.identityHashCode(i));
    24. if (i > 0) {
    25. try {
    26. Thread.sleep(100); // 模拟抢票延迟
    27. } catch (InterruptedException e) {
    28. e.printStackTrace();
    29. }
    30. // 2、张三此时的i = 7, 打印 “ 张三抢到了第7张票 ”
    31. // 3、计算i--,得到 i = 6导致i的hashcode发生改变,锁对象就发生的变化
    32. System.out.println(Thread.currentThread().getName() + "抢到了第" + i-- + "张票");
    33. } else {
    34. return;
    35. }
    36. }
    37. }
    38. }
    39. public static void main(String[] args) {
    40. TicketConsumer ticket = new TicketConsumer(new Integer(10));
    41. Thread t1 = new Thread(ticket, "张三");
    42. Thread t2 = new Thread(ticket, "李四");
    43. t1.start();
    44. t2.start();
    45. }
    46. }

    image.png