Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - Is it possible to interrupt Scanner.hasNext()

I've got a thread that reads user input and sends it over the network. The thread sits in a loop like this:

sin = new Scanner(System.in);

while (sin.hasNextLine()) {
    if (this.isInterrupted())
        break;

    message = sin.nextLine();

    // do processing...        
}

But when I try to interrupt the thread it doesn't exit the hasNextLine() method.

How can I actually quit this loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try replacing the the sin.hasNextLine with the method below. The idea behind is not to enter a blocking read operation unless there is data available on that stream.

I got the same problem a while ago and this fixes it. Basically, when you perform System.in.read() on a thread and from another thread you try to interrupt it, it won't work unless you press Enter. You might think that pressing any character should work, but that is not true, because it seems that the read operation inside os (or the jvm's hardware abstraction layer) only returns full lines.

Even System.in.available() won't return a non-zero value unless you press Enter as far as i know.

private boolean hasNextLine() throws IOException {
    while (System.in.available() == 0) {
        // [variant 1
        try {
            Thread.currentThread().sleep(10);
        } catch (InterruptedException e) {
            System.out.println("Thread is interrupted.. breaking from loop");
            return false;
        }// ]

        // [variant 2 - without sleep you get a busy wait which may load your cpu
        //if (this.isInterrupted()) {
        //    System.out.println("Thread is interrupted.. breaking from loop");
        //    return false;
        //}// ]
    }
    return sin.hasNextLine();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...