请第一次看到这个片段:主题 - 睡眠和中断
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);
}
}
主线程中断anotherThread。在我这样做后,countA不再是2x countB。他们现在总是相差一个。
为什么这么说?睡眠/中断如何工作?
你觉得中断怎么办?你读过javadoc吗? –
@ScaryWombat不要粗鲁,我认为这是有效的问题 – Betlista
@Betlista什么是粗鲁?我只是问两个问题。不知道答案是什么,我甚至不能回答这个问题。 –