设计模式学习-生产者消费者
-
生产者:生产数据(类、方法、线程、进程)
-
消费者:处理数据(类、方法、线程、进程)
-
缓冲区:仓库,生产者将数据放到仓库,消费者取数据,降低耦合
生产者和消费者模式的两种实现模式:
1、使用sychronized、wait()、notifyAll()
2、使用Lock(ReentrantLock)、await()、signal()
//生产者、消费者模式
public class TestPC {
public static void main(String[] args) {
synContainer syn = new synContainer();
new Thread(
()->{
for (int i = 1 ; i < 11; i++){
try {
TimeUnit.SECONDS.sleep(1);
syn.push(new Chicken(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产了" + i + "只鸡" );
}
}
).start();
new Thread(
()->{
for (int i = 1 ; i < 11; i++){
try {
System.out.println("消费了" + syn.pop().id+ "只鸡" );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
).start();
}
}
//生产者
/*class Productor extends Thread{
synContainer container ;
public Productor(synContainer synContainer){
this.container=synContainer;
}
@Override
public void run() {
for (int i = 0 ; i < 100; i++){
try {
container.push(new Chicken(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产了" + i + "只鸡" );
}
}
}*/
/*
//消费者
class Consumer extends Thread{
synContainer container ;
public Consumer(synContainer synContainer){
this.container=synContainer;
}
@Override
public void run() {
for (int i = 0 ; i < 100; i++){
try {
System.out.println("消费了" + container.pop().id+ "只鸡" );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
*/
//产品
class Chicken{
int id;
int num;
public Chicken(int id) {
this.id = id;
}
}
//容器
class synContainer{
//
int count = 0;
Chicken[] chickens = new Chicken[10];
ReentrantLock lock = new ReentrantLock();
Condition productSignal = lock.newCondition();
Condition consumerSignal = lock.newCondition();
//生产者放入,等待消费者消费
public void push (Chicken chicken) throws InterruptedException {
lock.lock();
try{
if(count == chickens.length){
//容器满了,通知消费者消费
productSignal.await();
}
// 容器没满,就继续放入产品
chickens[count] = chicken;
count ++;
//通知消费者消费
consumerSignal.signal();
}finally {
lock.unlock();
}
//此处为sychronized方法处理方式,用Thread的wait()和notifyAll()方法等待和唤醒
/* if(count == chickens.length){
//容器满了,通知生产者等一下消费
this.wait();
}
// 容器没满,就继续放入产品
chickens[count] = chicken;
count ++;
//通知消费者消费
this.notifyAll();*/
}
public Chicken pop() throws InterruptedException {
Chicken chicken = null;
lock.lock();
try{
//判断容器有值吗,没有就通知生产者生产
if(count ==0){
consumerSignal.await();
}
// 有值就处理数据
count--;
chicken = chickens[count];
//消费完通知生产者
productSignal.signal();
}finally {
lock.unlock();
}
//此处为sychronized方法处理方式,用Thread的wait()和notifyAll()方法等待和唤醒
/* //判断容器有值吗,没有就通知生产者生产
if(count ==0){
this.wait();
}
// 有值就处理数据
count--;
Chicken chicken = chickens[count];
//消费完通知消费者
this.notifyAll();*/
return chicken;
}
}