package com.concurrent;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class Apple {
private static AtomicInteger aid = new AtomicInteger(0);
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Apple() {
super();
this.id = aid.incrementAndGet();
}
}
class Producer implements Runnable {
private final BlockingQueue<Apple> queue;
public Producer(BlockingQueue<Apple> queue) {
// TODO Auto-generated constructor stub
this.queue = queue;
}
public void run() {
while (true) {
try {
Apple apple = produce();
TimeUnit.SECONDS.sleep(2);
queue.put(apple);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private Apple produce() {
Apple apple = new Apple();
System.out.println(" Put id = " + apple.getId());
return apple;
}
}
class Consumer implements Runnable {
private final BlockingQueue<Apple> queue;
public Consumer(BlockingQueue<Apple> queue) {
// TODO Auto-generated constructor stub
this.queue = queue;
}
public void run() {
while (true) {
try {
consume(queue.take());
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void consume(Apple a) {
System.out.println("Consume id = " + a.getId());
}
}
public class ProducerConsumer {
public static void main(String[] args) {
BlockingQueue<Apple> queue = new LinkedBlockingQueue<>();
Thread t1 = new Thread(new Producer(queue));
Thread t2 = new Thread(new Producer(queue));
Thread t3 = new Thread(new Consumer(queue));
t1.start();
t2.start();
t3.start();
}
}