您的位置:首页 > 编程语言 > Java开发

生产者消费者模式---java

2016-03-04 16:22 274 查看
/**

*

*/

import java.util.*;

public class PCModel {

public static void main(String[] args) {

Box box = new Box();

PAdd p1 = new PAdd(box);

PRemove p2 = new PRemove(box);

PAdd p3= new PAdd(box);

PRemove p4 = new PRemove(box);

PAdd p5 = new PAdd(box);

PRemove p6 = new PRemove(box);

p1.start();

p2.start();

p3.start();

p4.start();

p5.start();

p6.start();

}

}

class Box {

private static final int max = 10;

private List<Integer> list;

public Box(){

list = new ArrayList<>();

}

public void add() {

synchronized (list) {

while(list.size() >= max) {

System.out.println("盒子已满,等待删除!");

try {

list.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

list.add(1);

System.out.println("当前容量:" + list.size() + " --->" + Thread.currentThread().getName());

list.notifyAll();

}

}

public void remove() {

synchronized (list) {

while(list.size()==0){

System.out.println("盒子中没有产品,等待添加!");

try {

list.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

list.remove(0);

System.out.println("当前容量:" + list.size() + " --->" + Thread.currentThread().getName());

list.notifyAll();

}

}

}

class PAdd extends Thread{

private Box box;

public PAdd(Box box) {

this.box = box;

}

public void add() {

box.add();

}

public void run(){

for (int i = 0; i < 1000; i++) {

add();

}

}

}

class PRemove extends Thread{

private Box box;

public PRemove(Box box) {

this.box = box;

}

public void remove() {

box.remove();

}

public void run() {

for(int i=0; i<1000; i++){

remove();

}

}

}

运行结果:

盒子中没有产品,等待添加!

盒子中没有产品,等待添加!

当前容量:1 --->Thread-0

当前容量:2 --->Thread-0

当前容量:3 --->Thread-0

当前容量:4 --->Thread-0

当前容量:5 --->Thread-0

当前容量:6 --->Thread-0

当前容量:7 --->Thread-0

当前容量:8 --->Thread-0

当前容量:9 --->Thread-0

当前容量:10 --->Thread-0

盒子已满,等待删除!

当前容量:9 --->Thread-3

当前容量:8 --->Thread-3

当前容量:7 --->Thread-3

当前容量:6 --->Thread-3

当前容量:5 --->Thread-3

当前容量:4 --->Thread-3

当前容量:3 --->Thread-3

当前容量:2 --->Thread-3

当前容量:1 --->Thread-3

当前容量:0 --->Thread-3

盒子中没有产品,等待添加!

盒子中没有产品,等待添加!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: