线程的生产者消费者模式

生产者和消费者的简单案例


1.两个线程共享一个对象的资源;

2.生产者生产时,消费者需要等待,生产完了以后唤醒消费者,让生产者进入等待状态;

    消费者使用数据时,生产者要等待,消费者使用完了数据以后,唤醒生产者;

3.使用一个标识符来进行控制两个线程的状态

==============================================================================================================================

共享的类

package com.telneting.sychronized.productorandcustomer;

/**
 * 生产者和消费者共同使用的类数据
 * @author Andy
 *
 */
public class Dishes {
	private String name = null;
	//标识符号,控制线程是否等待
	private boolean flag = true;
	
	/**
	 * 生产食物的方法,让生产者进行调用
	 * @param food
	 */
	public synchronized void cook(String food){
		if(!flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		this.name = food;
		System.out.println("师傅正在做"+name);
		//让生产者等待
		this.flag = false;
		//唤醒消费者
		this.notify();
	}
	
	/**
	 * 消费食物的类,让消费者进行调用
	 */
	public synchronized void eat(){
		if(flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if(name != null){
			System.out.println("顾客正在吃"+name);
		}
		//唤醒生产者
		this.notify();
		//让消费者等待
		this.flag = true;
		
	}
	
	
	
}

生产者类


package com.telneting.sychronized.productorandcustomer;

public class Cook implements Runnable{
	private Dishes dishes;

	public Cook(){}
	
	public Cook(Dishes dishes){
		this.dishes = dishes;
	}
	
	@Override
	public void run() {
		for(int i=0; i<20; i++){
			if(i%2 == 0){
				dishes.cook("鱼香肉丝");
			}else{
				dishes.cook("麻辣鸡丝");
			}
		}
		
	}
	
}



消费者的类



package com.telneting.sychronized.productorandcustomer;

public class Customer implements Runnable{
	private Dishes dishes;
	
	public Customer(Dishes dishes) {
		this.dishes = dishes;
	}
	
	@Override
	public void run() {
		for(int i=0; i<20; i++){
			dishes.eat();
		}
		
	}
	
	
}

测试类

package com.telneting.sychronized.productorandcustomer;

public class Test {
	public static void main(String[] args) {
		Dishes dishes = new Dishes();
		Cook cook = new Cook(dishes);
		Customer customer = new Customer(dishes);
		new Thread(cook).start();
		new Thread(customer).start();
	}
}

显示的结果


..........


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值