生产者消费者问题


package com.wbs.Good;

public class Goods {
	private String name;
	private  boolean flag;//是否有产品,有的话生产者处于等待,消费者处于消费状态
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	//同步的生成商品方法
	public synchronized void set(String name){
		if(flag){
			try {
				super.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.name=name;
		flag=true;
		System.out.println("生产商品为:==========="+getName());
		super.notify();//唤醒取走的线程
	}
	//同步的取走商品方法
	public synchronized void get(){
		if(!flag){
			try {
				super.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		flag=false;
		System.out.println("取走商品为:========="+getName());
		super.notify();//唤醒生产的线程
	}
	

}

Productor类

package com.wbs.Good;

public class Productor implements Runnable {
	private Goods goods;
	public Productor(Goods goods){
		super();
		this.goods=goods;
	}
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			goods.set("电脑");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

Customer类

package com.wbs.Good;

public class Customer implements Runnable {
	Goods goods;
	public Customer (Goods goods){
		super();
		this.goods =goods;
	}
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			goods.get();//取走商品
		}
	}

}

Test类

package com.wbs.Good;

public class Test {
	public static void main(String[] args) {
		Goods goods=new Goods();
		Productor p=new Productor(goods);
		Customer c=new Customer(goods);
		new Thread(p).start();
		new Thread(c).start();
	}
}

测试截图


注:

object中专门对于同步代码块和同步方法的线程的方法:

wait();  //表示线程一直等待,直到其他线程通知

wait(long timeout);  //表示等待指定的毫秒数的时间

notify(); //唤醒一个处于等待状态的线程

notifyAll();//唤醒同一个对象的所有调用了wait()方法的线程,优先级别高的线程优先执行

以上方法都只能在同步方法和同步代码块中使用,否则会报错

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值