マルチスレッド通信(生産者、消費者問題)

マルチスレッドのコミュニケーションを理解し、それはリソースの共有を通じて通信スレッドを完了するために、複数のスレッドを共通の共有リソースを持っている必要があります使用することです。
例:プラント- -消費者製品
工場の製品、消費者製品、消費者製品は、二つの間の共有資源となっている
製品名、製品価格、農産物識別する必要があります。製品の属性のメンバー

public class Goods{
	private String name;
	private float price;
	private boolean product;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public boolean isProduct() {
		return product;
	}
	public void setProduct(boolean product) {
		this.product = product;
	}
	public Goods() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Goods(String name, float price, boolean product) {
		super();
		this.name = name;
		this.price = price;
		this.product = product;
	}
	
	
}

植物が生産する製品に農産物識別する必要があるかどうかに応じて、
裁判官は1を生成する必要があるかどうか
あなたは、アイデンティティの生産の変更に作るあなたが生成しない場合、消費者のスレッドをウェイクアップする必要がある場合は、起こされるのを待って、無限の待機状態に入ります

public class Produce implements Runnable {
	private Goods goods = null;

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true) {
			synchronized (goods) {
				
			
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		//需要生产
		if (goods.isProduct()) {
			if (Math.random() > 0.5) {
				goods.setName("擀面皮");
				goods.setPrice(6.0F);
			}else {
				goods.setName("烤羊排");
				goods.setPrice(128);
			}
			//修改标记
			goods.setProduct(false);
			System.out.println("生产者生产了"+goods.getName()+":"+goods.getPrice());
			//唤醒消费者
			goods.notify();
			System.out.println("需要唤醒消费者消费");

		}
		else {
			//生产者进人无限等待状态
			System.out.println("生产者进入无限等待");
			try {
				goods.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		}
		}
	}

	public Produce(Goods goods) {
		super();
		this.goods = goods;
	}

}

識別は、消費者代表の生産を必要としない必要性が無限待機を入力するには、消費者のプロセスを、それを生産する場合、消費者がウェイクを待って、生産プロセスをウェイク、アイデンティティの生産を修正することを消費者支出判断

public class Custmor implements Runnable {
	private Goods goods = null;

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true) {
		synchronized (goods) {
		
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		//判断是否可以进行消费
		if(!goods.isProduct()) {
			//更改生产状态
			goods.setProduct(true);
			System.out.println("消费者消费了"+goods.getName()+"花了"+goods.getPrice());
			//唤醒生产者生产
			System.out.println("唤醒生产者");
			goods.notify();
		}
		else {
			//让消费者进入等待
			System.out.println("消费者进入等待");
			try {
				goods.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		}
		}
	}

	public Custmor(Goods goods) {
		super();
		this.goods = goods;
	}

}
リリース8元の記事 ウォンの賞賛0 ビュー104

おすすめ

転載: blog.csdn.net/Lu_QQ/article/details/104630816