测试 synchronized 的买票案例

该代码示例展示了如何使用`synchronized`关键字处理多线程同步问题,以确保在卖票场景中不会出现数据不一致。创建了三个线程模拟购票,通过`ThreadPoolExecutor`执行,使用`LinkedBlockingQueue`作为工作队列。
摘要由CSDN通过智能技术生成
package com.ticketcase;


import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Author: Harry Chen
 * Date: 2023/02/13 16:25
 * Description: 测试 synchronized 的买票案例
 */
public class Test {
    private int count;

    public Test(int count) {
        this.count = count;
    }

    public synchronized void buyNum(int num) {
        while (count >= 1){
            this.count -= num;
            System.out.println("卖掉" + (this.count + num) + "号票。还剩:" + this.count);
        }
    }

    public static void main(String[] args) {

        Test test = new Test(100);

        Thread thread1 = new Thread(() -> {
            try {
                test.buyNum(1);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                test.buyNum(1);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread thread3 = new Thread(() -> {
            try {
                test.buyNum(1);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
        executor.execute(thread1);
        executor.execute(thread2);
        executor.execute(thread3);


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值