多线程生产者消费者代码

本文介绍了一个基于Java的生产者消费者模式实现,通过多线程和同步机制,演示了如何在生产者和消费者之间共享资源,确保线程安全。生产者负责生产食物,消费者负责消费,两者通过一个共享的食物对象进行交互。
public class Producers_Consumers {

	public static void main(String[] args) {
		//共同资源
		Food food = new Food();
		//多线程
		Producers p = new Producers(food);
		Consumers c = new Consumers(food);
		new Thread(p).start();
		new Thread(c).start();
	}

}

class Food{
	
	private String food;
	/*
	 * flag=true --> 生产者生产,消费者等待,通知消费者消费
	 * flag=false --> 消费者消费,生产者等待,通知生产者生产
	 */
	private boolean flag = true;
	
	public synchronized void making(String food){
		if(!flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//开始生产
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("生产者生产了"+food);
		//生产完毕
		this.food = food;
		//唤醒消费者
		this.notifyAll();
		//生产者停下
		this.flag = false;
	}
	
	public synchronized void eating(){
		if(flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//开始生产
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("消费者消费了"+food);
		//消费完毕,唤醒生产者
		this.notifyAll();
		//消费停止
		this.flag = true;
	}
	
}

class Producers implements Runnable{
	
	private Food food;
	
	public Producers(Food food){
		this.food = food;
	}
	
	public void run() {		
		for(int i=0; i<20; i++){
			if(i%2 == 0){
				food.making("糖醋排骨"+i);
			}else{
				food.making("红烧猪蹄"+i);
			}
		}
	}
	
}

class Consumers implements Runnable{
	
	private Food food;
	
	public Consumers(Food food){
		this.food = food;
	}
	
	public void run() {		
		for(int i=0; i<20; i++){
		    food.eating();
		}
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值