我只是即兴使用线程中断来取消线程。尽管在我的代码中两个线程都已停止,但看起来我没有捕捉到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
不咳嗽。它应该在 catch 块内打印中断消息,但没有打印任何内容