生产者消费者模式

本文介绍了一个使用Java实现的商品库存管理系统,通过线程同步和并发控制来管理库存更新。系统中包括了生成和消费商品的线程,以及商品库存的实时更新与显示。

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

import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JTextField; public class Store { private int count; private final int SIZE; private JFrame frame = new JFrame(); private JTextField[] fields = new JTextField[2]; public Store(int size) { this.SIZE = size; Producer producer = new Producer(this); Consumer consumer = new Consumer(this); producer.setName("生成了"); consumer.setName("消费了"); fields[0] = new JTextField(); fields[1] = new JTextField(); frame.add(fields[0], BorderLayout.NORTH); frame.add(fields[1], BorderLayout.SOUTH); producer.start(); consumer.start(); frame.pack(); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); frame.setVisible(true); } public void addData() { synchronized (this) { while (count == SIZE) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } fields[0].setText(Thread.currentThread().getName() + ++count + "件商品"); this.notifyAll(); } } public void removeData() { synchronized (this) { while (count == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } fields[1].setText(Thread.currentThread().getName() + count-- + "件商品"); this.notifyAll(); } } public static void main(String[] args) { Store s = new Store(5); } }
public class Producer extends Thread{ private Store s; public Producer(Store s){ this.s=s; } public void run(){ while(true){ s.addData(); try { Thread.sleep((int)(Math.random()*300)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class Consumer extends Thread{ private Store s; public Consumer(Store s){ this.s=s; } public void run(){ while(true){ s.removeData(); try { Thread.sleep((int)(Math.random()*300)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值