package CH11.d3;
import java.util.ArrayList;
import java.util.List;
public class XiaoFei {
static List<Integer> a=new ArrayList<>();
public final static Integer max=10;
static Object b=new Object();
static Object c=new Object();
public static void main(String[] args) {
shengchanzhe o=new shengchanzhe();
xiaofeizhe p=new xiaofeizhe();
o.setName("生产者:");
p.setName("消费者:");
o.start();
p.start();
}
}
class shengchanzhe extends Thread{
@Override
public void run() {
while (true){
synchronized (XiaoFei.b) {
if (XiaoFei.a.size() >= XiaoFei.max) {
try {
XiaoFei.b.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized (XiaoFei.c){
if (XiaoFei.a.size()>=5){
XiaoFei.c.notifyAll();
}
}
int r=(int)(Math.random()*5);
try {
Thread.sleep(r*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
XiaoFei.a.add(r);
System.out.println("生产者:"+XiaoFei.a);
}
}
}
class xiaofeizhe extends Thread{
@Override
public void run() {
while (true){
synchronized (XiaoFei.c) {
if (XiaoFei.a.isEmpty()) {
try {
XiaoFei.c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
int r=(int)(Math.random()*7);
XiaoFei.a.remove(0);
try {
Thread.sleep(r*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者:"+XiaoFei.a.remove(0));
synchronized (XiaoFei.b){
if (XiaoFei.a.size()<=5){
XiaoFei.b.notifyAll();
}
}
}
}
}