我只是即興使用線程中斷取消線程。雖然在我的代碼中兩個線程都停止了,但看起來我並沒有趕上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塊內的中斷消息,但沒有打印
這可能不應該有'Java的ee'標籤... – 2013-03-10 15:22:48
如何您認爲?中斷的線程是否可以檢查狀態? – 2013-03-10 15:28:30