Java:控制台应用程序主线程产生一个键侦听器线程 [英] java: console application main thread spawns a key listener thread

查看:86
本文介绍了Java:控制台应用程序主线程产生一个键侦听器线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个工具,它正在执行一些步骤1..n 其中一些步骤需要用户交互(从System.in中读取) 循环执行其他步骤,直到满足某些条件或用户按下某个键 (当用户按下键时,循环应结束,主循环应进行下一步)

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)

我为那些提供键循环中断的步骤所做的就是生成一个从System.in中读取的线程->如果按下了键,则该线程会中断该步骤. 这可以正常工作,但是当满足循环条件时,此关键侦听器线程将在System.in上阻塞,因此下一步需要用户交互的步骤将受到影响

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

推荐答案

当我将侦听器线程更改为:

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 :)

这篇关于Java:控制台应用程序主线程产生一个键侦听器线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆