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 + "Ready to consume products:");
Product product = storage.pop();
System.out.println(name + "consumed" + product.toString());
System.out.println("=======Consumed ========");
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)); // Generate random integers from 0 to 9999
System.out.println(name + "Ready to produce(" + product.toString() + ").");
s.push(product);
System.out.println(name + "produced (" + product.toString() + ").");
System.out.println("=======produced========");
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("Zhang San", s);
Producer p2 = pc.new Producer("Li Si", s);
Consumer c = pc.new Consumer("Wang Wu", s);
Consumer c2 = pc.new Consumer("Old Liu", s);
Consumer c3 = pc.new Consumer("Old Lin", s);
service.submit(p);
service.submit(p2);
service.submit(c);
service.submit(c2);
service.submit(c3);
}
}