中断运行线程

时间:2013-03-10 15:15:34

标签: java multithreading interrupt

我只是即兴使用线程中断进行线程取消。虽然在我的代码中两个线程都被停止了,但看起来我没有抓住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块中打印中断消息但是没有打印

2 个答案:

答案 0 :(得分:3)

您有一个无界的队列,因此生产者和消费者都没有被阻塞在队列中。因此,没有可能抛出InterruptedException的操作被中断。

答案 1 :(得分:1)

这是中断的例子:

公共类TestThread1实现了Runnable {

public void run() {
    while(Thread.currentThread().isInterrupted() == false) {
        System.out.println("dans la boucle");

        //on simule une courte pause

        for(int k=0; k<100000000; k++);

        System.out.println("Thread isInterrupted = " + Thread.currentThread().isInterrupted());
    }
}

public static void main(String[] args) {
    Thread t = new Thread(new TestThread1());
    t.start();

    //on laisse le temps à l'autre Thread de se lancer
    try {
        Thread.sleep(1000);

    } catch(InterruptedException e) {}

    System.out.println("interruption du thread");
    t.interrupt();
}

}

执行结果是:

  

dans la boucle

     

Thread isInterrupted = false

     

dans la boucle

     

interruption du thread

     

Thread isInterrupted = true