BlockingQueue


请输入图片描述

   
  import java.util.concurrent.BlockingQueue;
  
public class Producer extends Thread {
private BlockingQueue<String> bQueue;
public Producer(String name,BlockingQueue<String> bQueue){
super(name);
this.bQueue = bQueue;
}
@Override
public void run() {
String[]que = {"java","c#","c++"};
for (int i = 0; i < 99999999; i++) {
String objString = que[i%3];
try {
Thread.sleep(1000);
this.bQueue.put(objString);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"完成生产产品"+bQueue);
}
}
}

public class Consumer extends Thread{
private BlockingQueue<String> bQueue ;
public Consumer(String name,BlockingQueue<String> bQueue){
super(name);
this.bQueue = bQueue;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
this.bQueue.take();

} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"消费产品"+bQueue);
}
}
}
public class Test {
public static void main(String[] args) {
BlockingQueue<String> bQueue = new ArrayBlockingQueue<>(1);
new Producer("111",bQueue).start();
new Producer("222",bQueue).start();
new Producer("333",bQueue).start();
new Consumer("消费者",bQueue).start();
}
}

问题,阻塞队列我想要每次最多只能生产一个产品,然后由消费者去消耗。但我的运行结果发现可以生产多个,然后消费多个.



相关链接

多线程

偶是loli 10 years, 2 months ago

因为你对blockingqueue 的操作 和后面的打印, 这两个操作 不是原子的.

其实一个producer的时候, 你就可以看到你说的"生产多个,然后消费多个".
举例说,
consumer 等待, producer bQueue.put(objString)后, consumer被释放;
接下来, 究竟是producer还是consumer 先做打印操作就完全随机了.

cnm1994 answered 10 years, 2 months ago

Your Answer