import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
//阻塞队列实现生产者和消费者
public class BlockQueueTest {
public static void main(String[] args) {
BlockingQueue<Object> queue = new LinkedBlockingQueue<>(10);
Provider p = new Provider(queue);
Consumer c = new Consumer(queue);
Consumer c2 = new Consumer(queue);
new Thread(p).start();
new Thread(c).start();
new Thread(c2).start();
}
public static class Provider implements Runnable{
private BlockingQueue<Object> queue ;
public Provider(BlockingQueue<Object> queue){
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
queue.put(new Object());
System.out.println("生产者"+Thread.currentThread().getName()+"生产了一个产品,先库存"+ queue.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static class Consumer implements Runnable{
private BlockingQueue<Object> queue ;
public Consumer(BlockingQueue<Object> queue){
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
queue.take();
System.out.println("消费者"+Thread.currentThread().getName()+"消费了一个产品,先库存"+ queue.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}