如果我运行以下程序,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();
}
}
答案 0 :(得分:1)
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()
答案 1 :(得分:0)
额外的“接受”阻止终止。它阻止了额外的“采取”