主要是判断条件 从if 换成 while
1.生产者
public class Productor extends Thread {
Syncontainer syncontainer;
public Productor(Syncontainer syncontainer) {
this.syncontainer = syncontainer;
}
@Override
public void run() {
try {
this.syncontainer.push(new Chicken(Thread.currentThread().getId()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
2.消费者
public class Consumer extends Thread{
Syncontainer syncontainer;
public Consumer(Syncontainer syncontainer) {
this.syncontainer = syncontainer;
}
@Override
public void run() {
try {
this.syncontainer.pop();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
3.生产对象
public class Chicken {
long id;
public Chicken(long id) {
this.id = id;
}
public long getId() {
return this.id;
}
}
4.缓冲区
public class Syncontainer {
//产品容器缓冲区容量10
Chicken[] chickens = new Chicken[10];
int count = 0;
//放入产品
public synchronized void push(Chicken chicken) throws InterruptedException {
//容器满了 不可以再加入
if (count == chickens.length) {
System.out.println("装不下了chicken,请等等");
this.wait();
}
// try {
chickens[count] = chicken;
count++;
System.out.println("生产了chicken:" + chicken.getId());
this.notify();
// }catch (Exception e){
// System.out.println("生产异常线程:"+Thread.currentThread().getName());
// }
//
}
//消费者消费
public synchronized void pop() throws InterruptedException {
System.out.println("消费线程:"+Thread.currentThread().getName());
while (count <= 0) {
System.out.println("暂无可消费chicken,请等等");
this.wait();
}
// try{
count--;
System.out.println("消费了chicken:" + chickens[count].getId());
// }catch (Exception e){
// System.out.println("消费异常线程:"+Thread.currentThread().getName());
// }
}
}
5.运行(使用固定容量线程池)
public class Case1 {
public static void main(String[] args) {
ExecutorService e = Executors.newFixedThreadPool(5);
Syncontainer syncontainer = new Syncontainer();
for (int i = 0; i < 20; i++) {
e.execute(new Productor(syncontainer));
e.execute(new Consumer(syncontainer));
// new Consumer(syncontainer).start();
// new Productor(syncontainer).start();
}
}
}