最初にこのスニペットを見てください:
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つ異なります。
なんでそうなの?スリープ/割り込みはどのように機能しますか?