gpt4 book ai didi

java - LinkedBlockingQueue 程序不会终止

转载 作者:行者123 更新时间:2023-12-01 12:48:36 30 4
gpt4 key购买 nike

如果我运行以下程序,JVM 在执行后不会终止。但是,如果我取消代码中 (//newFixedThreadPool.execute(new Producer3());) 行的注释,程序将在执行后终止。我知道由于队列的阻塞性质,程序不会终止。在以下代码的上下文中,哪部分代码阻止了 JVM 的终止?

public class LinkedBlockingQueueExample {

public static void main(String[] args) {

final BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>(5);

final class Producer implements Runnable {

@Override
public void run() {

try {
blockingQueue.put("Joshua");
blockingQueue.put("Bloch");
System.out.println("Put Joshua in the queue");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

final class Producer1 implements Runnable {

@Override
public void run() {

try {
blockingQueue.put("Martin");
blockingQueue.put("Fowler");
System.out.println("Put Mr Fowler in the Queue");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

final class Producer3 implements Runnable {

@Override
public void run() {

try {
blockingQueue.put("Malcom");
blockingQueue.put("Gladwell");
System.out.println("Put an Outlier in the Queue");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

final class Consumer implements Runnable {

@Override
public void run() {
try {
System.out.println(getClass() + " " + blockingQueue.take());
System.out.println(getClass() + " " + blockingQueue.take());
System.out.println(getClass() + " " + blockingQueue.take());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

final class Consumer1 implements Runnable {

@Override
public void run() {
try {
System.out.println(getClass() + " " + blockingQueue.take());
System.out.println(getClass() + " " + blockingQueue.take());
System.out.println(getClass() + " " + blockingQueue.take());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(5);

newFixedThreadPool.execute(new Producer());
newFixedThreadPool.execute(new Producer1());
// newFixedThreadPool.execute(new Producer3());
newFixedThreadPool.execute(new Consumer());
newFixedThreadPool.execute(new Consumer1());

newFixedThreadPool.shutdown();

}
}

最佳答案

Take() 调用始终处于阻塞状态,直到元素可用为止。如果您不想阻止,则用户 poll()

    poll()
Retrieves and removes the head of this queue, or returns null if this queue is empty.

引用:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html#poll()

关于java - LinkedBlockingQueue 程序不会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437736/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com