2

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

4

2 回答 2

3

您有一个无界队列,因此生产者和消费者都不会被阻塞在队列中。因此,不会中断任何可能引发 InterruptedException 的操作。

于 2013-03-10T15:21:17.417 回答
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 boule

线程 isInterrupted = false

dans la boule

线程中断

线程 isInterrupted = true

于 2013-03-10T15:25:02.027 回答