一、wait/notify实现
class Goods{
Integer maxcount;
Integer count;
public Goods(Integer maxcount, Integer count) {
this.maxcount = maxcount;
this.count = count;
}
public synchronized void consumers() {
if(count>0){
count--;
System.out.println("消费者"+Thread.currentThread().getName()+": "+count);
notifyAll();
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void product() {
if(count< maxcount){
count++;
System.out.println("生产者"+Thread.currentThread().getName()+": "+count);
notifyAll();
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Produce extends Thread{
Goods goods;
public Produce(Goods goods){
this.goods = goods;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
goods.product();
}
}
}
class Custom extends Thread{
Goods goods;
public Custom(Goods goods) {
this.goods = goods;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
goods.consumers();
}
}
}
public static void main(String[] args) {
Goods goods = new Goods(10, 0);
Produce produce = new Produce(goods);
produce.setName("生产者1");
Custom custom = new Custom(goods);
custom.setName("消费者1");
Custom custom2 = new Custom(goods);
custom2.setName("消费者2");
custom.start();
produce.start();
custom2.start();
}