asynchronous UI in java
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 fromRuntime.exec(String)
has methods for getting theInputStream
for both stderr and stdout and theOutputStream
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 stdoutOutputStream
. 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 theOutputStream
and can be read by the stdin of the external process.
Good luck.
精彩评论