執行緒協作(生產者消費者模式)
阿新 • • 發佈:2022-04-15
sleep不會釋放鎖,wait會釋放鎖
檢視程式碼
package com.lei.study03; //測試:生產者消費者模型-->利用緩衝區解決:管程法 //生產者,消費者,產品,緩衝區 public class TestPc extends Thread{ public static void main(String[] args) { SynContainer synContainer = new SynContainer(); new Productor(synContainer).start(); new Customer(synContainer).start(); } } //生產者 class Productor extends Thread { SynContainer container; public Productor(SynContainer container) { this.container = container; } //生產 @Override public void run() { for (int i = 1; i <=100; i++) { System.out.println("生產了第" + i + "只雞"); container.push(new Chicken(i)); } } } //消費者 class Customer extends Thread{ SynContainer container; public Customer(SynContainer container){ this.container=container; } //消費 @Override public void run() { for (int i = 1; i <=100; i++) { System.out.println("消費了第-->"+container.pop().id+"只雞"); } } } //產品 class Chicken{ int id;//產品編號 public Chicken(int id) { this.id = id; } } //緩衝區 class SynContainer{ //需要一個容器大小 Chicken[] chickens=new Chicken[10]; //計數器 int count=0; //生產者放入產品 public synchronized void push(Chicken chicken){ //如果容器滿了,則等待消費者消費 if(count==chickens.length){ //通知消費者消費,生產等待 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //如果沒有滿則丟入產品 chickens[count]=chicken; count++; //可以通知消費者消費了 this.notifyAll(); } //消費者消費產品 public synchronized Chicken pop(){ //判斷能否消費 if(count==0){ //等待生產者生產,消費者等待 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //如果可以消費 count--; Chicken chicken=chickens[count]; this.notifyAll(); //吃完了,通知生產者生產 return chicken; } }