java: console application main thread spawns a key listener thread

…衆ロ難τιáo~ 提交于 2019-12-08 13:09:24

问题


I wrote a tool, which is performing some steps 1..n Some of the steps require user interaction (reading from System.in) Other steps loop until some condition is fulfilled or the user pressed some key (When the user pressed the key the loop should end and the main should go to the next step)

What I did for those steps, that provide a key loop interruption is to spawn a thread which reads from System.in -> this thread then interrupts the step, if key was pressed. This works fine, but when the loop condition was fulfilled, then this key listener thread would block on System.in, so the next step, that requires user interaction would be affected

My key listener thread's run was basically:

new InputStreamReader(System.in).read() > 0;

which blocks of course, so I was looking for a way to fix this


回答1:


And when I change the key listener thread to:

try
{
InputStreamReader reader = new InputStreamReader(System.in);
while (!reader.ready()) { Thread.sleep(100); }
if (reader.read() > 0) { // interrupt this step and proceed to the next one }
}
catch (IOException e) { // do something }
catch (InterruptedException e) { // noone needs me anymore }

And after the step loop I just interrupt the key listener thread, since it is not needed anymore.

So this worked fine for me and since I didn't find a solution for such problems, wanted to post it here for the future generations :)



来源:https://stackoverflow.com/questions/11521597/java-console-application-main-thread-spawns-a-key-listener-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!