package com.my.demo;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Random;
import java.util.Scanner;
public class ProducerConsumerDemo {
public static void main(String args[]) {
LinkedList<Integer> buffer = new LinkedList<>();
new Producer(buffer, "P1").start();
new Consumer(buffer, "C1").start();
new Consumer(buffer, "C2").start();
new Consumer(buffer, "C3").start();
}
}
class Producer extends Thread {
private LinkedList<Integer> list;
public Producer(LinkedList<Integer> list, String name) {
super(name);
this.list = list;
}
@Override
public void run() {
try {
Scanner scanner = new Scanner(System.in);
while (true) {
String line = scanner.nextLine();
if (line.startsWith("p")) {//produce. example: p8->produce 8 items
fillList(Integer.parseInt(line.substring(1)));
} else if (line.startsWith("b")) {//break producer.
break;
}
}
scanner.close();
System.out.println(getName() + " exit.");
} catch (Exception e) {
System.out.println(getName() + " Producer exception.");
}
}
private void fillList(int count) {
synchronized (list) {
for (int n = 0; n < count; n++) {
//如果list已满,则等待
if (list.size() >= 20) {
try {
System.out.println(getName() + " List is full, Producer wait.");
list.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
//如果list没有满,则继续生产
Random random = new Random();
int i = random.nextInt(90) + 10;
list.add(i);
list.notifyAll();
}
}
}
}
class Consumer extends Thread {
private LinkedList<Integer> list;
public Consumer(LinkedList<Integer> list, String name) {
super(name);
this.list = list;
}
@Override
public void run() {
while (true) {
synchronized (list) {
if (list.isEmpty()) {
System.out.println(getName() + " List is empty, Consumer wait.");
try {
list.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println(getName() + " Consuming: " + list.removeLast() + ", list.size=" + list.size() + ", list=" + Arrays.toString(list.toArray()));
list.notifyAll();
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(getName() + " Consumer interrupted");
}
}
}
}
ProducerConsumerDemo
点赞
收藏