スレッドの中断を使用したスレッドのキャンセルを即興で行っています。私のコードでは両方のスレッドが停止していますが、私はキャッチしていないようですが、InterruptedException
なぜだろうか?
プロデューサー:
public class Producer implements Runnable{
private BlockingQueue<String> queue ;
public Producer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()){
queue.put("Hello");
}
}catch (InterruptedException e) {
System.out.println("Interupting Producer");
Thread.currentThread().interrupt();
}
}
}
消費者:
public class Consumer implements Runnable {
BlockingQueue<String> queue;
public Consumer(BlockingQueue<String> queue) {
super();
this.queue = queue;
}
@Override
public void run() {
String s;
try {
while (!Thread.currentThread().isInterrupted()) {
s = queue.take();
System.out.println(s);
}
} catch (InterruptedException e) {
System.out.println("Consumer Interupted");
Thread.currentThread().interrupt();
}
}
}
そして今メイン:
public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
Thread producerThread = new Thread(new Producer(queue));
Thread consumerThread = new Thread(new Consumer(queue));
producerThread.start();
consumerThread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
} finally {
producerThread.interrupt();
consumerThread.interrupt();
}
}
糸は止まりますが、なぜInterruptedException
咳が出ないのかわかりません。キャッチブロック内に割り込みメッセージを出力するはずですが、何も出力されません