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咳が出ないのかわかりません。キャッチブロック内に割り込みメッセージを出力するはずですが、何も出力されません

4

2 に答える 2

3

無制限のキューがあるため、プロデューサーもコンシューマーもキューでブロックされません。したがって、InterruptedException をスローする可能性のある操作は中断されません。

于 2013-03-10T15:21:17.417 に答える
1

中断の例を次に示します。

public class 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();
}

}

実行結果は次のとおりです。

ダンス・ラ・ブークレ

スレッド isInterrupted = false

ダンス・ラ・ブークレ

スレッドの中断

スレッド isInterrupted = true

于 2013-03-10T15:25:02.027 に答える