java生产者消费者核心代码

本文介绍了一个基于Java实现的生产者消费者模式案例。通过使用synchronized关键字和wait()、notify()方法来控制多线程间的同步,确保生产和消费操作的正确顺序执行。该案例有助于理解多线程环境下如何解决资源竞争问题。

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


/* @src http://eric-619.iteye.com/blog/693680
* java多线程:生产者消费者核心程序代码及wait()---notify()、notifyAll()方法应用测试
* 把消费者来回跑的次数多,更能体现出多线程的次序性(测试次序正确性的原则)
* notify()方法开启对方线程!!!,因为对方有wait()
*/


public class ProCon{
public static void main(String[] args){
SyncStack stack = new SyncStack();
Consumer p = new Consumer(stack);
Producer c = new Producer(stack);
You y = new You(stack);
new Thread(c).start();
new Thread(y).start();
new Thread(p).start();
}
}

class Producer implements Runnable{
private SyncStack stack;

public Producer(SyncStack stack){
this.stack = stack;
}

public void run(){
for (int i = 0; i < stack.pro().length; i++){
stack.push("产品"+i);
}
}
}

class You implements Runnable{
SyncStack s;
public You(SyncStack s){
this.s = s;
}
public void run(){
for(int i = 0; i < s.pro().length; i++){
new SyncStack().yp();
}
}
}

class Consumer implements Runnable{
private SyncStack stack;

public Consumer(SyncStack stack) {
this.stack = stack;
}

public void run(){
for(int i = 0; i < stack.pro().length; i++){
System.out.println(stack.pop());
}
}
}


class SyncStack{
private String[] str = new String[10];
private int index;



public synchronized String pop(){
if(index == 0){
try{
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
//notify();
return "消费了-------------------"+str[--index];
}

public synchronized void push(String sst){

//notifyAll();
str[index] = sst;
index ++;
System.out.println("生产了:"+sst);
}

public synchronized void yp(){
// if(index == 0){
// try{
// wait();
// }catch (InterruptedException e){
// e.printStackTrace();
// }
// }
System.out.println("凑凑热闹的!!!!!!!!!!!"+"------"+index);
}

public String[] pro(){
return str;
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值