This is related to some other questions on here, but I haven't yet seen an answer that helps. (EDIT by JWW: per the comments, the cited duplicate doe not handle the EOF
as expected or desired).
In this example, the main()
function starts a Thread, which blocks on a Scanner's nextLine()
function. I then wait for 0.2 s, and after that time I want to force this Thread to terminate, even though nothing's been typed in. I can't get the Thread to stop on its own, without hitting a key to satisfy its Scanner.
import java.util.*;
class sandbox {
public static void main(String[] args) {
BlockingThread thread = new BlockingThread();
thread.start();
trySleep(200); // wait 0.2 s
thread.closeScanner(); // try to close the Scanner, to terminate the Thread
}
public static void trySleep(int time) {
try { Thread.sleep(time); }
catch (InterruptedException e) {}
}
static class BlockingThread extends Thread {
private Scanner scanner = new Scanner(System.in);
public void run() {
System.out.println("Running!");
scanner.nextLine();
System.out.println("Stopping!");
}
public void closeScanner() {
System.out.println("\tTrying to close the Scanner...");
scanner.close();
System.out.println("\tScanner is now closed.");
}
}
}
Some notes:
- It's definitely blocking on the Scanner's underlying stream. If you download and run this code, it'll halt right after printing "Trying to close the Scanner..." If you remove the call to
thread.closeScanner()
, it'll stop immediately after "Running!" - I've seen some answers claiming that I want to call the Thread's
interrupt()
method. But that doesn't work, because the Thread is blocked. - I've seen other answers claiming that I want to close the stream that the
Scanner
is reading. But that doesn't seem to work either—Scanner
docs indicate that itsclose()
method closes the underlying stream, so that should be what I'm doing in the above toy code. - I'd even be willing to use a deprecated method like
stop()
, but even that appears to have no effect.
Any ideas? Thanks.
(If you're curious, the underlying motivation is to create an automated grader for my students' work. The stream will ultimately be the stdout of a process being executed by a thread. But some of my students will have infinite loops, and I want the thread to terminate after n seconds, even if the process hasn't completed. So deadlock isn't really a concern, since I'm really not doing much in the way of synchronization.)