import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
/**
*
* @author hack's home
* @date 2020/10/8
*/
public class ProducerConsumer {
private class Product {
private int id;
public Product(int id) {
this.id = id;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
'}';
}
}
private class Storage {
BlockingQueue<Product> productBlockingQueue = new LinkedBlockingQueue<>();
public void push(Product product) {
try {
productBlockingQueue.put(product);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Product pop() {
try {
return productBlockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
class Consumer implements Runnable {
private String name;
private Storage storage;
public Consumer(String name, Storage storage) {
this.name = name;
this.storage = storage;
}
@Override
public void run() {
while (true) {
System.out.println(name + "准备消费产品:");
Product product = storage.pop();
System.out.println(name + "已消费" + product.toString());
System.out.println("=======已消费========");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer implements Runnable {
private String name;
private Storage s = null;
public Producer(String name, Storage s) {
this.name = name;
this.s = s;
}
@Override
public void run() {
try {
while (true) {
Product product = new Product((int) (Math.random() * 10000)); // 产生0~9999随机整数
System.out.println(name + "准备生产(" + product.toString() + ").");
s.push(product);
System.out.println(name + "已生产(" + product.toString() + ").");
System.out.println("=======已生产========");
Thread.sleep(500);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
Storage s = pc.new Storage();
ExecutorService service = Executors.newCachedThreadPool();
Producer p = pc.new Producer("张三", s);
Producer p2 = pc.new Producer("李四", s);
Consumer c = pc.new Consumer("王五", s);
Consumer c2 = pc.new Consumer("老刘", s);
Consumer c3 = pc.new Consumer("老林", s);
service.submit(p);
service.submit(p2);
service.submit(c);
service.submit(c2);
service.submit(c3);
}
}