public class ProducerAndConsumer {
private static final int MAX_PRODUCE_COUNT = 10;
/**
* */
public static void main(String[] args) {
TakeAndPut tp = new TakeAndPut();
Producer p = new Producer(tp, MAX_PRODUCE_COUNT);
Consumer c = new Consumer(tp, MAX_PRODUCE_COUNT);
Thread p1 = new Thread(p);
Thread c1 = new Thread(c);
p1.start();
c1.start();
}
}
class TakeAndPut {
private boolean Flag = false; // 判断产品是否生产好了
public synchronized void put(int number) {
System.out.println(" The Producer have done the " + number
+ " product ");
while (Flag == true) { // 产品生产好了
try {
wait(); // 生产者等消费者消费
} catch (InterruptedException e) {
e.printStackTrace(); // 追踪异常事件发生时执行堆栈的内容
System.out.println(e.toString()); // 打印输出异常的信息的简短描述
}
}
Flag = true; // 设置生产好标志为true
notifyAll(); // 通知消费者消费
}
public synchronized void take(int number) {
while (Flag == false) { // 产品没生产好的情况下
try {
wait(); // 等待生产者生产
} catch (InterruptedException e) {
e.printStackTrace(); // 追踪异常事件发生时执行堆栈的内容
System.out.println(e.toString()); // 打印输出异常的信息的简短描述
}
}
System.out.println(" The Consumer can consume the " + number
+ " product");
Flag = false; // 设置生产好的标志为false
notifyAll(); // 通知生产者可以生产
}
}
class Producer implements Runnable {// 生产者线程类
TakeAndPut tp;
int MAX_PRODUCE_COUNT; // 最大生产量
public Producer(TakeAndPut tp, int max) {
this.tp = tp;
this.MAX_PRODUCE_COUNT = max;
}
public void run() {
for (int i = 0; i < MAX_PRODUCE_COUNT; i++) {
try {
Thread.sleep((int) Math.random() * 2000); // 设定随机休眠时间
} catch (InterruptedException e) {
e.printStackTrace(); // 追踪异常事件发生时执行堆栈的内容
System.out.println(e.toString()); // 打印输出异常的信息的简短描述
}
tp.put(i); // 调用put方法,执行线程之间的通信
}
}
}
class Consumer implements Runnable { // 消费者线程类
TakeAndPut tp;
int MAX_PRODUCE_COUNT; // 最大生产量
public Consumer(TakeAndPut tp, int max) {
this.tp = tp;
this.MAX_PRODUCE_COUNT = max;
}
public void run() {
for (int i = 0; i < MAX_PRODUCE_COUNT; i++) {
try {
Thread.sleep((int) Math.random() * 2000); // 设定随机休眠时间
} catch (InterruptedException e) {
e.printStackTrace(); // 追踪异常事件发生时执行堆栈的内容
System.out.println(e.toString()); // 打印输出异常的信息的简短描述
}
tp.take(i); // 调用take方法,执行线程之间的通信
}
}
}