开发者

asynchronous UI in java

开发者 https://www.devze.com 2023-01-05 12:07 出处:网络
I\'m working on a Java program, and it\'s been over a year since the last time I used Java, so I\'m a little rusty.This program uses Runtime.exec() to call other programs to do its dirty work, and nee

I'm working on a Java program, and it's been over a year since the last time I used Java, so I'm a little rusty. This program uses Runtime.exec() to call other programs to do its dirty work, and needs to parse their output and update its own GUI accordingly in real time while the other programs are working. What's the best way to do this? I'm currently thinking of having my external-program-executor class have its own internal thread that polls the external program's output stream and then raises events when noteworthy things happen, and then开发者_StackOverflow中文版 implementing my own EventListener interface for my UI classes. I worry however how that will handle the asynchronous nature of the events being fired. Can anyone give any tips on how to protect the listeners from race conditions, and/or a better approach? Thanks.


  • You don't have to poll for output in the external process. The Process object returned from Runtime.exec(String) has methods for getting the InputStream for both stderr and stdout and the OutputStream for stdin.
  • You can communicate by sending messages over the OutputStream. Simply push your data on the stream.
  • Spawn a Thread that waits on the stdout OutputStream. Everytime there is new data to read, it will read the data and create an event.
  • Dispatch the event using the Event Dispatcher Thread, EDT. It's used by the Swing/AWT GUI too, so no problems there.
  • You can also use events for sending stuff to the stdin. Simply create an EventListener that listens for certain output events. These events are (possibly translated to a different format) onto the OutputStream and can be read by the stdin of the external process.

Good luck.

0

精彩评论

暂无评论...
验证码 换一张
取 消