生产者消费者模型

1,仓库类
public class WareHouse {

private ArrayList<String> list = new ArrayList<>();

private Integer i = 0;
/**
* 向集合中添加元素
*/
public synchronized String add(){
if(list.size()<20){
list.add(i+++"");
}else{
//return;
try {
this.notifyAll();//唤醒全部线程,可根据设置的优先级唤醒顺序
this.wait();//进入等待(阻塞)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(list.size()>0){
return list.get(list.size()-1);
}else{
return "";
}
}

/**
* 从集合中取出元素
*/
public synchronized String get(){
String name = "";
if(list.size()>0){
name = list.remove(0);
}else{
//return;
try {
this.notifyAll();//唤醒全部线程,可根据设置的优先级唤醒顺序
this.wait();//进入等待(阻塞)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return name;
}
}

2,消费者类
public class Consumer extends Thread{

private String name;

private WareHouse house;


public Consumer(String name,WareHouse house){
this.name = name;
this.house = house;
}

public void run(){
String houseName = null;
while(true){
houseName = house.get();
System.out.println(this.name+"拿走了一件货物。。"+houseName);
try {
this.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3,生产者类
public class Producer extends Thread{

private String name;

private WareHouse house;

public Producer(String name,WareHouse house){
this.name = name;
this.house = house;
}

public void run(){
String houseName = null;
while(true){
houseName = house.add();
System.out.println(this.name+"生产了一件货物。。"+houseName);
try {
this.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}
posted @ 2020-06-12 14:49  EspenWu  阅读(140)  评论(0编辑  收藏  举报