简体   繁体   中英

Clear Scanner(in)

on my code, I've a long loop of sequential operation. I make a thread to stop this loop manually. Basically

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;
        }

    }

and the thread basically is waiting on the standard input for stop character

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;
            }   
            }
        }

    }
}

The problem is that, if the loop exit normally, the thread is locked on the scanner.next, so, the next input is lose inside the still dead thread. How to release the scanner.next from main class? I've tried with scan.close() but doesn't work...

There's another way to stop the loop, without kill the application? i try with keyListener, but i've got a null pointer

您是否尝试过使用scan.close()或scanner.close()?

This seems to be a case where using Thread.interrupt is a valid occasion. Once the processing is successful, do a stopChecker.interrupt - that should fail the Scanner.next with a ClosedByInterruptException exception. Note that according to javadoc System.in might be closed because of this operation.

If that is not an option, the only solution is to not to use Scanner and do your option read in a non-blocking way.

Please change the code as follows.

1) Replace while loop with do - while block

2) Change Scanner code as follows

 do{
    while ( scanner.hasNext() ) {
         String command = scanner.nextLine();
         System.out.println("line:"+command);
    }
 } while ( conditionFlag)

When the condition is false, call

scanner.close(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM