在我的代码中,我有一个很长的顺序操作循环。 我创建了一个线程来手动停止这个循环。 基本上
private static void sendAndCheck() throws InterruptedException {
stop = false;
StopChecker r = new StopChecker();
Thread t = new Thread( r );
if ( vettore != null ) {
t.start();
for ( int i = 0; i < vettore.length; i++ ) {
do {
if ( stop == true ) {
break;
}
//Do something for a lot of time.. (code deleted)
} while ( !status.equalsIgnoreCase( "PROCESSED" ) ); //<- normal exit
}
//Stop the thread
stop = true;
}
}
线程基本上正在等待标准输入的停止字符
public class StopChecker implements Runnable {
public void run() {
Scanner scanner = new Scanner( System.in );
System.out.println( "1 - to stop" );
while ( !Risottometti.stop ) {
String command = scanner.next();
if ( command.equalsIgnoreCase( "1" ) ) {
Risottometti.stop = true;
}
}
}
}
}
问题是,如果循环正常退出,线程将被锁定在 Scanner.next 上,因此,下一个输入将在仍然死的线程内丢失。 如何从主类中释放scanner.next? 我尝试过 scan.close() 但不起作用...
还有另一种方法可以停止循环而不终止应用程序吗?我尝试使用 keyListener,但我有一个空指针
最佳答案
这似乎是使用 Thread.interrupt 的有效场合。处理成功后,执行 stopChecker.interrupt
- 这将使 Scanner.next
失败,并出现 ClosedByInterruptException
异常。请注意,根据 javadoc System.in
可能会因为此操作而关闭。
如果这不是一个选项,唯一的解决方案是不使用Scanner
并以非阻塞方式读取您的选项。
关于java - 透明扫描仪(中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32223982/