生产者消费者模型:
代码:
主类:
package a0506.Test4;
public class Test4 {
public static void main(String[] args) {
Basket basket=new Basket(5);
Producter p1=new Producter(basket);
Producter p2=new Producter(basket);
Consume c1=new Consume(basket);
Consume c2=new Consume(basket);
new Thread(p1,"------生产者1------").start();
new Thread(p2,"------生产者2------").start();
new Thread(c1,"------消费者1------").start();
new Thread(c2,"------消费者2------").start();
}
}
媒介(篮子):
package a0506.Test4;
import java.util.ArrayList;
import java.util.List;
public class Basket {
private List<String> list=new ArrayList<>();
private int maxSize;
public Basket(int maxSize) {
this.maxSize = maxSize;
}
public void produce(String name){
synchronized (list){
while(list.size()==this.maxSize){
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("\n"+Thread.currentThread().getName()+"生产商品:"+name);
list.add(name);
System.out.println("篮子所有商品: "+list.toString());
list.notifyAll();
}
}
public void consume(){
synchronized (list){
while(list.size()==0){
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("\n"+Thread.currentThread().getName()+"开始消费: ");
String goods=list.get(list.size()-1);
list.remove(list.size()-1);
System.out.println("\n消费商品是: "+goods);
list.notifyAll();
}
}
}
生产者:
package a0506.Test4;
import javax.swing.*;
public class Producter implements Runnable{
private Basket basket;
public Producter(Basket basket) {
this.basket = basket;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
String name= JOptionPane.showInputDialog("请输入生产商品名");
if("over".equalsIgnoreCase(name))
break;
this.basket.produce(name);
}
}
}
消费者:
package a0506.Test4;
public class Consume implements Runnable{
private Basket basket;
public Consume(Basket basket) {
this.basket = basket;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.basket.consume();
}
}
}
理解:
媒介(篮子):
篮子自身的最大容量;
产品放入集合和产品从集合中拿走
生产者:
篮子,对哪个篮子生产,调用篮子自身的方法把产品放进去
消费者:
篮子,对哪个篮子消费,调用篮子自身的方法把产品拿走(消费)