multithreading - Stopping a Java thread blocked on a Scanner -


this related other questions on here, haven't yet seen answer helps. (edit jww: per comments, cited duplicate doe not handle eof expected or desired).

in example, main() function starts thread, blocks on scanner's nextline() function. wait 0.2 s, , after time want force thread terminate, though nothing's been typed in. can't thread stop on own, without hitting key satisfy 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 close scanner, terminate 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 close scanner...");             scanner.close();             system.out.println("\tscanner closed.");         }     } } 

some notes:

  • it's blocking on scanner's underlying stream. if download , run code, it'll halt right after printing "trying close scanner..." if remove call thread.closescanner(), it'll stop after "running!"
  • i've seen answers claiming want call thread's interrupt() method. doesn't work, because thread blocked.
  • i've seen other answers claiming want close stream scanner reading. doesn't seem work either—scanner docs indicate close() method closes underlying stream, should i'm doing in above toy code.
  • i'd willing use deprecated method stop(), appears have no effect.

any ideas? thanks.

(if you're curious, underlying motivation create automated grader students' work. stream stdout of process being executed thread. of students have infinite loops, , want thread terminate after n seconds, if process hasn't completed. deadlock isn't concern, since i'm not doing in way of synchronization.)

i think scanner wrong tool job. the documentation says:

a scanning operation may block waiting input.

oh, , more importantly:

a scanner not safe multithreaded use without external synchronization.

you should use code in answer instead: how interrupt java.util.scanner nextline call


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -