多线程之售票问题

该博客通过一个Java多线程程序演示了模拟售票的过程,使用`synchronized`关键字确保线程安全。程序创建了2000个线程模拟多人购票,每个线程随机购买1-5张票,最终统计剩余票数和售出票数。此示例展示了并发编程中同步控制的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @Author: MiaoXiaoQiang
 * @Date: 2021/8/21 16:23
 *
 * synchronized this  锁住对象,因为是对一个对象的多次操作
 */
public class ExerciseTransfer {
    public static void main(String[] args) throws InterruptedException {
        //模拟多人买票
        TicketWindow ticketWindow = new TicketWindow(10000);
        //为了让所有线程运行结束后再统计相关结果 需要对线程进行相关的控制
        List<Thread> threadList = new ArrayList<>();
        //售出票数总和
        List<Integer> amountList = new Vector<>();
        for (int i = 0; i <2000 ; i++) {
            Thread thread = new Thread(()->{
                //买票
                int amount = ticketWindow.sell(randomAmount());
                amountList.add(amount);
            });
            threadList.add(thread);
            thread.start();
        }
        for (Thread thread : threadList) {
            thread.join();
        }
        //统计相关票数
        System.out.println("剩余票数:" + ticketWindow.getCount());
        System.out.println("售出票数:" + amountList.stream().mapToInt(i->i).sum());

    }
    //Random 为线程安全
    static Random random = new Random();
    //随机购买票数 随机 1-5
    public static int randomAmount(){
        return random.nextInt(5) + 1;
    }

}

class TicketWindow{
    //成员变量
    private int count;
    //有参构造方法
    public TicketWindow(int count){
        this.count = count;
    }
    //get方法 获取剩余票数量
    public int getCount(){
        return count;
    }
    //售票
    public synchronized int sell(int amount){
        if (this.count >= amount){
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值