如果我运行以下程序,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();
}
}发布于 2014-06-26 18:36:38
额外的“索取”阻碍了终止。它阻塞了额外的“拿走”
发布于 2014-07-01 11:22:37
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()
https://stackoverflow.com/questions/24437736
复制相似问题