这个模型主要体现了多线程里面的线程间的通信。
生产者来生产产品,再通知消费者来进行消费,若容量满,就阻塞生产者线程。
消费者来消费产品,如果没有产品,则消费者线程进入阻塞状态。有产品消费了后就通知生产者进行生产。
生产者、消费者都是单独的线程,缓冲区是线程的共享空间,且该空间的访问是需要同步操作的
下面是个对这个模型的图解
代码实现如下:
import java.util.LinkedList;
import java.util.Random;
/*
生产者来生产产品,再通知消费者来进行消费,若容量满,就阻塞生产者线程。
消费者来消费产品,如果没有产品,则消费者线程进入阻塞状态。有产品消费了后就通知生产者进行生产。
生产者、消费者都是单独的线程,缓冲区是线程的共享空间,且该空间的访问是需要同步操作的
*/
public class Productor extends Thread {
private LinkedList<Integer> C;
private Random random=new Random();
public Productor(LinkedList<Integer> C){
this.C=C;
}
@Override
public void run(){
while(true){
synchronized(C){
while(C.size()==2){
System.out.println("产品满了请消费者来消费");
try {
C.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int count=random.nextInt(500); //随机生成500内的整数
System.out.println("给仓库放"+count);
try {
Productor.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//将数据放入仓库中
C.addLast(count);
//通知消费者线程
C.notifyAll();
}
}
}
static class Consumer extends Thread{
private LinkedList<Integer> C;
private Random random=new Random();;
public Consumer(LinkedList<Integer> C){
this.C=C;
}
@Override
public void run (){
while(true){
synchronized (C){
while(C.size()==0){
System.out.println("产品为空,请求生产者生产");
try {
C.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer count=C.removeFirst();
System.out.println("消费者消费了产品"+count);
//通知生产者线程
C.notifyAll();
try {
Consumer.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
LinkedList<Integer> C=new LinkedList<Integer>();
Productor productor=new Productor(C);
Consumer consumer=new Consumer(C);
productor.start();
consumer.start();
}
}
最后演示一下程序运行结果:
差不多就是这样