请先看这个片段:
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 循环中添加一行:
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);
}
}
主线程中断另一个线程。在我这样做之后,countA 不再是 2x countB。他们现在总是相差一个。
为什么这样?睡眠/中断如何工作?