在我的代码中,我有一个很长的顺序操作循环。我创建了一个线程来手动停止这个循环。基本上
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,但我有一个空指针