生产者和消费者之间,生产者生产了消费者才有东西消费,他们之间的控制都来自于Object类的成员方法 3
wait阻塞会释放锁
首先引入一个生产者消费者模型
/*
* 协作模式:生产者消费者实现方式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 void push(produce p) {
ps[count++] = p;
}
//消费
public produce pop() {
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;
}
}
以上代码没有同步机制
给缓冲区容器的生产和消费成员方法加上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;
}
}
当产品没有时,消费者阻塞等待生产者生产后通知唤醒消费者,当缓冲区空间不够时,生产者阻塞,等待消费者消费后唤醒生产者继续消费