阻塞队列实现的生产者/消费者模式

本文介绍了一个基于Java实现的多线程售票系统案例。该系统通过一个共享的阻塞队列来同步多个售票点线程与票务生产者线程之间的交互。文章详细展示了如何使用synchronized关键字和wait/notify机制确保线程安全。

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

public class MyThread {
    static int i;
    public static void main(String[] args) {
        TickOffice t = new TickOffice();
        Thread t1 = new Thread(new Produce(t));
        t1.setName("售票点1");
        t1.start();
        Thread t2 = new Thread(new Consumer(t));
        t2.setName("售票点2");
        t2.start();
        Thread t3 = new Thread(new Consumer(t));
        t3.setName("售票点3");
        t3.start();
        Thread t4 = new Thread(new Consumer(t));
        t4.setName("售票点4");
        t4.start();
    }
}
class TickOffice {
    private int ticket = 0;
    private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(15); //存放5张票的阻塞队列
    public synchronized void add(){
        if(this.queue.size()>=15){
            System.out.println("仓库已满");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            ticket += 1;
            try {
                queue.put(ticket);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("产生第"+ticket+"张票");
            this.notifyAll();
        }
    }
    public synchronized void get(){
        if(this.queue.size()<=0){
            System.out.println("缺票等待中");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println(Thread.currentThread().getName()+"售出第"+queue.poll()+"张票");
            this.notifyAll();
        }
    }
}
class Produce implements Runnable{
    private TickOffice off;
    public Produce(TickOffice off) {
        this.off = off;
    }
    @Override
    public void run() {
        System.out.println("开张");
        while (true) {
            
            off.add();
        }
    }
    
}

class Consumer implements Runnable{
    private TickOffice off;
    public Consumer(TickOffice off) {
        this.off = off;
    }
    @Override
    public void run() {
        System.out.println("消费者开始取走产品");
        while(true){
            
            off.get();
        }
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值