我指的是BlockingQue的概念,我找到一个示例here。BlockingQueue程序不会退出
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; /* j a v a 2s . co m*/
public class Main {
public static void main(String[] argv) throws Exception {
int capacity = 10;
BlockingQueue <Integer> queue = new ArrayBlockingQueue <Integer> (capacity);
int numWorkers = 2;
Worker[] workers = new Worker[numWorkers];
for (int i = 0; i < workers.length; i++) {
workers[i] = new Worker(queue);
workers[i].start();
}
for (int i = 0; i < 10; i++) {
queue.put(i);
}
}
}
class Worker extends Thread {
BlockingQueue <Integer> q;
Worker(BlockingQueue <Integer> q) {
this.q = q;
}
public void run() {
try {
while (true) {
Integer x = q.take();
if (x == null) {
break;
}
System.out.println(x);
}
} catch (InterruptedException e) {}
}
}
在这个例子中,他们只使用了一个工作线程的线程。
我对BlockingQue
的理解是,它是生产者 - 消费者模式的替代解决方案。
所以我们需要两个线程来处理。因此我有疑问/问题。
以下是我的问题。
他们使用主线程作为另一个线程吗?
当我运行该应用程序时,程序不会退出。我不明白主程序为什么不退出?