有没有一种优雅的方式在从
System.in
接收到字符时触发事件?我想避免轮询InputStream.available()
。InputStream stdin = System.in;
// Create a wrapper (with it's own dedicated read-thread)
MyListenableInputStream listenableInputStream =
new MyListenableInputStream(stdin);
// Update System.in with something more useful.
System.setIn(listenableInputStream);
当然可以...开启一个线程,在输入上阻塞并在获取到数据后调用您的事件方法。
总的来说:
如果您已经有一个事件反应器在运行,请创建一个线程并让它阻塞在read()
上。当有数据可用时,让该线程将一个事件加入队列以供反应器处理。如果您无法这样做,大多数事件反应器都提供了InvokeLater
或CallLater
方法,供您在事件处理线程中运行一些代码。
在通知或调度函数调用后,返回到阻塞在read()
上。
new Thread(){
public void run() {
while(System.in.get()){
}
}.start();