public class ProducerConsumer {
//产品
static class Product {
String name;
public Product(String n) {
this.name = n;
}
@Override
public String toString() {
return name;
}
}
//阻塞队列
static BlockingQueue<Product> queue = new LinkedBlockingDeque<>(10);
//生产者
static class Producer implements Runnable {
String name;
public Producer(String name) {
this.name = name;
}
void produce(Product p) throws InterruptedException {
//阻塞等待,等有空间放则返回
queue.put(p);
//放入成功则返回 true,失败则返回 false
//queue.offer(p);
System.out.println("生产:" + p.name);
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
produce(new Product("" + i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
static class Consumer implements Runnable {
String name;
public Consumer(String name) {
this.name = name;
}
void consume() throws InterruptedException {
//阻塞等待
Product p = queue.take();
//没有则返回 null
//Product p = queue.poll();
System.out.println("消费:" + p.name);
}
@Override
public void run() {
try {
consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//测试
public static void main(String[] args) {
Consumer consumer = new Consumer("消费者");
Producer producer = new Producer("生产者");
for (int i = 0; i < 5; i++) {
new Thread(consumer, "消费者线程" + i).start();
new Thread(producer, "生产者线程" + i).start();
}
}
}
#笔试题目#