我的测试似乎不支持您的发现。它按预期工作!
我编写了以下演示代码
public class DemoThread extends Thread {
Scanner sin = new Scanner(System.in);
@Override
public void run() {
while (sin.hasNextLine()) {
if(this.isInterrupted()) {
System.out.println("Thread is interrupted.. breaking from loop");
break;
}
String message = sin.nextLine();
System.out.println("Message us " + message);
// do processing...
}
}
public static void main(String args[]) throws InterruptedException {
DemoThread thread = new DemoThread();
thread.start();
Thread.sleep(5000);
thread.interrupt();
}
}
输出是
a
Message us a
s
Message us s
asd
Thread is interrupted.. breaking from loop
所以请再次检查。此外,如果您对输出 asd 感到困惑,那么它是来自上一个循环迭代的字符串输入,在该点线程没有被中断。如果你不想这样做,你可以这样做
if(!this.isInterrupted()) {
String message = sin.nextLine();
}
Why is this happening?
可以说在迭代中线程没有被中断,因此它进入了while循环(hasNext()由于先前迭代中读取的字符串而通过)。它检查线程是否被中断(可以说它不是在这个时间点)并继续到下一行(从标准输入扫描新字符串)。现在让我们说线程被中断。您的程序将等到您输入一些字符串(您必须在控制台中按 Enter 键)。因此,即使线程中断,也会读取字符串,并且该字符串将用于评估 hasNext() 操作(将评估为真),并且上下文将进入 while 循环。在这里它将看到线程被中断并中断。
为避免这种情况,您需要在 if(!this.isInterrupted()) 语句中读取字符串。请参阅我上面的代码。