我正在使用java.util.concurrent
包并使用其接口/类来了解它们的工作原理。我创建了一个BlockingQueue
实例(ArrayBlockingQueue
imlpementation)。并创建了50个消费者和50个Rannable
类型的生产者。然后用Executors.newFixedThreadPool(4)
创建一个大小为4的线程池,并将我的所有使用者/生成者提交给threadPool
(ExecutorService)。但最终打印过程我认为它是deadlock
- ing。任何人都可以解释为什么线程安全队列陷入僵局!?以下是我的代码:
消费者:
public class ArrayBlockingQueueConsumer implements Runnable{
BlockingQueue<Integer> blockingQueue;
int consumerNumber = 0;
public ArrayBlockingQueueConsumer(BlockingQueue<Integer> blockingQueue, int consumerNumber) {
this.blockingQueue = blockingQueue;
this.consumerNumber = consumerNumber;
}
public void run() {
int i = 0;
while(i<60) {
System.out.printf("Consumer %d going take %d from blocking queue\n", consumerNumber, i);
try {
int x = blockingQueue.take();
System.out.println("The number " + x + "is taken from the queue.");
} catch (InterruptedException e) {
System.out.printf("Consumer %d interrupted while adding %d to blocking queue\n", consumerNumber, i);
e.printStackTrace();
}
i++;
}
}
}
制片:
public class ArrayBlockingQueueProducer implements Runnable{
BlockingQueue<Integer> blockingQueue;
int producerNumber = 0;
public ArrayBlockingQueueProducer(BlockingQueue<Integer> blockingQueue, int producerNumber) {
this.blockingQueue = blockingQueue;
this.producerNumber = producerNumber;
}
public void run() {
int i = 0;
while(i<60) {
System.out.printf("Consumer %d going to add %d to blocking queue\n", producerNumber, i);
blockingQueue.add(i);
System.out.printf("Consumer %d added %d to blocking queue\n", producerNumber, i);
i++;
}
}
}
执行者类(main()方法类):
public class BlockingQueueExecutor {
public static void main(String[] args) {
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(50);
ArrayBlockingQueueConsumer[] consumers = new ArrayBlockingQueueConsumer[200];
ArrayBlockingQueueProducer[] producers = new ArrayBlockingQueueProducer[200];
System.out.println("Hello hello :D");
for (int i = 0; i < 200; i++) {
consumers[i] = new ArrayBlockingQueueConsumer(blockingQueue, i+1);
producers[i] = new ArrayBlockingQueueProducer(blockingQueue, i+1);
}
ExecutorService threadPool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 200; i++) {
threadPool.execute(consumers[i]);
threadPool.execute(producers[i]);
}
threadPool.shutdown();
}
}
我在消费者/生产者中运行从0到60的循环,这样他们就可以在找不到任何元素或分别找到队列时抛出异常,具有讽刺意味的是,没有一个生产者/消费者抛出任何异常。
答案 0 :(得分:3)
当队列为空时,我在消费者/生产者中运行从0到60的循环,这样当他们找不到任何元素或分别找到满队列时他们就会抛出异常,具有讽刺意味的是,没有一个生产者/消费者抛出任何异常。
take()
不会抛出异常。它等待一个元素可用。
E java.util.concurrent.BlockingQueue.take()抛出InterruptedException
检索并删除此队列的头部,必要时等待,直到元素可用。
答案 1 :(得分:2)
这里没有死锁。您的代码在IllegalStateException
来电中为我投了BlockingQueue.add()
。这导致队列没有像计划的那样完整,最终导致take()
阻止,如记录所示。没死锁。
死锁是两个或多个线程无法继续进行的情况,因为它们都在等待彼此。