java 线程模拟生产者和消费者

本文通过Java线程模拟了经典的生产者消费者问题。代码中定义了一个共享缓冲区,两个线程分别扮演生产者和消费者角色,使用synchronized块及wait/notify机制协调生产与消费过程,展示了多线程同步的基本原理。

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

生产者和消费者问题是操作系统里面的一个经典问题,用java线程可以来模拟实现。知识点参考:

http://blog.youkuaiyun.com/lazy_p/archive/2010/06/02/5642657.aspx

代码如下:

package test1; public class ConsumerAndProducer { private int[] buffer = new int[10]; private int index = -1; private String SIGNAL1 = "SIGNAL";//互斥信号量 private String SIGNAL2 = "SIGNAL";//互斥信号量 public static void main(String[] args) { ConsumerAndProducer cp = new ConsumerAndProducer(); cp.new Producer().start(); cp.new Consumer().start(); } private class Producer extends Thread { private void product() { buffer[++index] = index; System.out.println("生产:" + index); } @Override public void run() { while (true) { synchronized (SIGNAL2) { if (index < 9) product(); else { System.out.println("wait Producer"); try { // sleep(1000); SIGNAL1.notify(); SIGNAL2.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } private class Consumer extends Thread { private void consume() { --index; System.out.println("消费" + buffer[index + 1]); } @Override public void run() { while (true) { synchronized (SIGNAL1) { if (index >= 0) { consume(); } else { System.out.println("wait consumer"); try { // sleep(1000); SIGNAL2.notify(); SIGNAL1.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值