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, 1 month ago