package com.zqb.bean3;
public class Test07 {
public static void main(String[] args) {
AppleBox ab = new AppleBox();
Produce p = new Produce(ab);
Consumer c = new Consumer(ab);
Thread t = new Thread(p);
t.start();
Thread t2 = new Thread(c);
t2.start();
}
}
// 生产者
class Produce implements Runnable {
AppleBox appleBox;
public Produce(AppleBox appleBox) {
this.appleBox = appleBox;
}
@Override
public void run() {
// 生产10个苹果到AppleBox中
for (int i = 1; i <= 10; i++) {
Apple a = new Apple(i);
appleBox.deposite(a);
System.out.println(Thread.currentThread().getName() + "生产了" + a);
try {
Thread.sleep((int) Math.random() * 10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 消费者
class Consumer implements Runnable {
AppleBox appleBox;
public Consumer(AppleBox appleBox) {
this.appleBox = appleBox;
}
@Override
public void run() {
// 消费10个苹果
for (int i = 1; i <= 10; i++) {
Apple a = appleBox.withdraw();
System.out.println(Thread.currentThread().getName() + "消费了" + a);
try {
Thread.sleep((int) Math.random() * 10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class AppleBox {
int index = 0;
Apple[] apples = new Apple[5];
public synchronized void deposite(Apple apple) {
// 判断apples是否满了,满了,则不能再存
while (index >= apples.length) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 没满则存
notifyAll();
apples[index] = apple;
index++;
}
public synchronized Apple withdraw() {
// 判断apples是否空了,空了,则不能再取
while (index == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 没空则取
notifyAll();
Apple a = apples[index - 1];
index--;
return a;
}
}
class Apple {
int id;
Apple(int id) {
this.id = id;
}
public String toString() {
return "apple" + id;
}
}
生产者与消费者
最新推荐文章于 2024-05-16 05:24:05 发布