本篇学习的是线程通信的管程法,设置缓冲区,以生产者和消费者 为场景。
package lesson04;
/**
* 生产者消费者模型:利用缓冲区---->管程法
*/
public class TestCP {
public static void main(String[] args) {
SyContiner continer = new SyContiner();
Productor productor = new Productor(continer);
Customer customer = new Customer(continer);
productor.start();
customer.start();
}
}
//生产者
class Productor extends Thread {
SyContiner continer;
public Productor(SyContiner continer) {
this.continer = continer;
}
@Override
public void run() {
//生产产品
for (int i = 0; i < 100; i++) {
continer.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
class Customer extends Thread {
SyContiner continer;
public Customer(SyContiner continer) {
this.continer = continer;
}
//消费产品
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println("消费了"+continer.pop().id+"只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//产品
class Chicken {
int id ;
public Chicken(int id) {
this.id = id;
}
}
//缓冲器:容器
class SyContiner {
//设置容器大小
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.notify();
}
//消费者消费产品
public synchronized Chicken pop () throws InterruptedException {
if (count == 0) {
//等待生产者生产
this.wait();
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完通知生产者生产
this.notify();
return chicken;
}
}