I know Thread.stop()
is deprecated and interrupt()
or a way to use inner variable should be used.
However, https://stackoverflow.com/a/10962613/3809427 says "InputStream/OutputStream
which are not interruptable" and I think thread waiting input can’t be terminated by a way using inner variable. Following is an example.
Thread labelThread = Thread.ofVirtual().unstarted(() -> {
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
});
labelThread.start();
System.out.println("start");
Thread.sleep(3000);
labelThread.interrupt();
Thread.sleep(1000);
System.out.println(labelThread.isInterrupted());
System.out.println(labelThread.isAlive());
Output is following if you don’t input any.
start
isInterrupted= true
isAlive= true
If you input any(e.g. ‘a’), thread is terminated.
start
a
isInterrupted= true
isAlive= false
Actual process I want to terminate is inputReader()
of external app and above is simplified code.
In these cases, stop()
is only way to terminate thread? I can’t completely understand following answer but stop()
gives a negative impact on entire system, not only thread even if thread is as simple as above?
java – Thread.stop() – deprecated – Stack Overflow
You need to sign in to view this answers
Leave feedback about this