2

最初にこのスニペットを見てください:

public static void main(String[] args) throws InterruptedException {
    Thread anotherThread = new Thread(() -> {
        Integer countB = 0;
        while (true) {
            try {
                System.out.println("B count: " + ++countB);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    anotherThread.start();

    Integer countA = 0;
    while (true) {
        System.out.println("A count: " + ++countA);
        Thread.sleep(1000);
    }
}

これは期待どおりに機能します。countA は countB の約 2 倍であることがわかります。

ここで、外側の while ループに 1 行追加します。

public static void main(String[] args) throws InterruptedException {
    Thread anotherThread = new Thread(() -> {
        Integer countB = 0;
        while (true) {
            try {
                System.out.println("B count: " + ++countB);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    anotherThread.start();

    Integer countA = 0;
    while (true) {
        anotherThread.interrupt();
        System.out.println("A count: " + ++countA);
        Thread.sleep(1000);
    }
}

メイン スレッドが anotherThread に割り込みます。これを行った後、countA はもはや 2x countB ではありません。現在、それらは常に1つ異なります。

なんでそうなの?スリープ/割り込みはどのように機能しますか?

4

4 に答える 4

0

これは正しいバディの答えへの追加です。

最初のケースでは、

B    A
.    .
.    A
.    .
B    A
.    .
.    A
.    .
B    A

しかし、割り込みで次のように変更されました:

B    A (interrupts B, B continues in loop)
B    .
.    A (interrupts B again)
B    .
.    A
B    .
.    A
B    .
.    A

Bを2秒待たせないようにする...

于 2015-12-02T07:34:58.593 に答える