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
盒子中没有产品,等待添加!
盒子中没有产品,等待添加!