多线程-并发抢票案例

本次案例:模拟并发抢票

情景:300用户争夺100张门票

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class ExerciseSellTicket {
    private static Random random = new Random();

    public static void main(String[] args) throws InterruptedException {

        //票数
        TicketWindow ticketWindow = new TicketWindow(100);
        ExecutorService executorService = Executors.newCachedThreadPool();

        List<Integer> sellCount = new CopyOnWriteArrayList<Integer>();
        CountDownLatch countDownLatch = new CountDownLatch(300);
        //模拟多线程争抢
        for (int i = 0; i < 300; i++) {
            executorService.submit(()->{
                countDownLatch.countDown();
                int sellTicket = ticketWindow.sellTicket(randomAmount());
                sellCount.add(sellTicket);
            });
        }

        //阻塞main线程
        countDownLatch.await();
        executorService.shutdownNow();

        log.info("本次卖出 {} 张票",sellCount.stream().mapToInt(c->c).sum());
        log.info("剩余 {} 张票",ticketWindow.getCount());

    }

    // 随机 1~3
    public static int randomAmount() {
        return random.nextInt(3) + 1;
    }
}

//卖票窗口
class TicketWindow {
    //共享资源,总票数
    private int count;

    public TicketWindow(Integer count) {
        this.count = count;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    //成员变量count是共享变量,
    // 对于我们而言,只需要保证同一时刻,只有一个线程能拿到count的值,进行操作,==》就可以达到同步的效果。
    public synchronized int sellTicket(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值