控制台应用程序中的 Java 键盘输入解析
我刚刚开始使用 JLine 在控制台模式下解析字符输入.它似乎运作良好,但我想知道:
I've just started messing around with JLine to parse character input in console mode. It seems to work well, but I'm wondering:
在 JLine 中是否有一种非阻塞方式来确定字符是否可用?(即像 kbhit()
在 Windows 中.)
Is there a nonblocking way in JLine to find out if characters are available? (i.e. like kbhit()
in Windows.)
我想我总是可以将键盘输入包装在它自己的线程中,然后在线程安全队列中将键盘字符提供给主线程,但这似乎是不必要的.
I suppose I could always wrap keyboard input in its own thread which then offers the keyboard characters in a thread-safe queue to the main thread, but that seems like it should be unnecessary.
EDIT:这是逐个字符的解析.我不会使用 GUI.Java 中控制台模式下通常的 InputStream I/O 要求您先按 Enter 键(例如,它只是缓冲输入).请不要告诉我在控制台模式下逐个字符输入在 Java 中是不可能的;不是.JLine 使用具有平台相关实现的可移植接口来实现.
EDIT: This is character-by-character parsing. I am not going to use a GUI. The usual InputStream I/O in Java in console mode requires you to hit the Enter key first (e.g. it's buffered input only). Please don't tell me character-by-character input in console mode is impossible in Java; it isn't. JLine does it using a portable interface with a platform-dependent implementation.
编辑更新:我能够组合一个帮助类来在工作线程中执行阻塞 I/O(使用 JLine 进行每个字符的 I/O,警告:你必须自己解析 Ctrl-C!) &然后通过一个带有 isempty() 例程的同步队列进行通信.对于我现在正在做的事情,这很好,但我真的很想知道在未来做这件事的好方法.
Edit update: I was able to hack together a helper class to do the blocking I/O in a worker thread (using JLine for the per-character I/O, warning: you have to parse Ctrl-C yourself!) & then communicate via a synchronized queue with an isempty() routine. For what I'm doing right now that's fine, but I would really like to know a Good Way To Do This In The Future.
推荐答案
你似乎走对了.
我认为执行此操作的正确"方法是使用工作线程将所有阻塞 I/O 倒入非阻塞队列中.看看 ConcurrentLinkedQueue 来自 java.util.并发.
I think the "right" way to do this is a worker thread that pours all the blocking I/O into a non-blocking queue. Hava a look at ConcurrentLinkedQueue from java.util.concurrent.
相关文章