2
我有非常簡單的代碼,它使用「毒丸」模擬生產者/消費者停止技術。使用毒藥丸不能阻止生產者/消費者線程
我有監製類:
public class Producer extends Thread {
private final BlockingQueue<String> queue;
public Producer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
//unblocking this line will cause the code to stop after intrrupt
//System.out.println("1");
queue.put("hello world");
}
} catch (InterruptedException e) {
try {
queue.put(Main.POISON_PILL);
} catch (InterruptedException e1) {
}
}
}
}
消費階層:
public class Consumer extends Thread {
private final BlockingQueue<String> queue;
public Consumer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
String s = queue.take();
if (s.equals(Main.POISON_PILL))
break;
else
System.out.println(s);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
現在的主要功能:
public static String POISON_PILL = "POISON_PILL";
public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
producer.start();
consumer.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
} finally {
producer.interrupt();
}
}
因爲即使producer.interrupt()
稱爲後不知道原因, 「你好世界「永遠在控制檯上進行打印。
我無法理解的第二件事是爲什麼取消註釋System.out.println("1");
將導致程序在生產者線程中斷後退出。
請幫我理解爲什麼。
您也可以在發佈藥丸之前排空隊列。 – OldCurmudgeon 2013-03-19 00:11:06
你是對的。 – 2013-03-19 00:13:58