管程法的特点是,生产者和消费者 1中间有一个缓冲区 2
以上代码没有同步机制
给缓冲区容器的生产和消费成员方法加上synchronized,并且加上是否可以继续生产以及可以消费的逻辑控制,增加线程等待和唤醒
package zy.thread.cooperation; /* * 协作模式:生产者消费者实现方式1:管程法 */ public class coTest01 { public static void main(String[] args) { synContainer container = new synContainer(); new productor(container).start(); new consumer(container).start(); } } //生产者 class productor extends Thread{ private synContainer container; public productor(synContainer container) { super(); this.container = container; } public void run() { for(int i=0; i<10; ++i) { container.push(new produce(i)); System.out.println("生产第"+i+"个产品"); } } } //消费者 class consumer extends Thread{ private synContainer container; public consumer(synContainer container) { super(); this.container = container; } public void run() { for(int i=0; i<10; ++i) { container.push(new produce(i)); System.out.println("消费第"+container.pop().getId()+"个产品"); } } } //缓冲区 class synContainer{ produce[] ps = new produce[10]; //计数 int count = 0; //生产 public synchronized void push(produce p) { //不能生产 if(count >= ps.length) { try { this.wait(); // //线程阻塞,消费者通知解出 } catch (InterruptedException e) { } } ps[count++] = p; this.notify(); //通知消费者消费 } //消费 public synchronized produce pop(){ //不能消费 if(count == 0) { try { this.wait(); //线程阻塞,生产者通知解出 } catch (InterruptedException e) { } } this.notify(); //通知生产者生产 return ps[--count]; } } //产品 class produce{ private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public produce(int id) { super(); this.id = id; } }当产品没有时,消费者阻塞等待生产者生产后通知唤醒消费者,当缓冲区空间不够时,生产者阻塞,等待消费者消费后唤醒生产者继续消费
生产者和消费者同时有多个因此时多线程 ↩︎
由并发容器作缓冲区 ↩︎
wait 、notify、notifyAll ↩︎