我只是即兴使用线程中断取消线程。虽然在我的代码中两个线程都停止了,但看起来我并没有赶上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