My question pertains to multi-threading in Java. I’m translating an app I wrote in Visual Basic 2008 into Java. There is a class in VB called BackgroundWorker, which allows the coder to perform a task on another thread, a lot like SwingWorker in Java. The only distinct difference is that, with the BackgroundWorker thread is run(), it fires an event called DoWork() on the mainline which contains the code to execute in the background. Furthermore, after the code has executed, a RunWorkerCompleted() event is fired back on the foreground thread to interpret results.
I have found the BackgroundWorker setup quite useful and it seems a little more flexible than SwingWorker and I was just wondering whether it was possible (and acceptable) to fire events in the same way in Java? And if so, how would I go about it? Since I’ve only done a quick scan over SwingWorker, it’s possible that it has a similar functionality that would work just as well, in which case I would be happy to know about that instead.
Cheers,
Hoopla
EDIT:
Kewl. Cheers guys, thanks for the prompt replies, and apologies for my rather time-lax reply. I’ll give your idea a go Oscar, sorry coobird, I didn’t quite follow – any further explanation would be welcome (perhaps an example).
Just to recap: I want to have a runnable class, that I instantiate an instance of in my code. The runnable class has two events, one of which is fired from the background thread and contains the code to run in the background (DoWork()), and the other event is fired on the foreground thread after the background thread has completed it’s task (RunWorkerCompleted()).
And if I understand your advice correctly, I can fire the DoWork() event from the runnable class’ run() method so that it will be executed on the background thread, and then I can use the SwingUtilities.invokeLater() method to fire the RunWorkerCompleted() event on the foreground thread, once the background thread has finished execution.
Yes?
The solely intention of the following code is to show how does it looks like when the SwingUtilities.invokeLater method is used.
The effect is the task is executed in the AWT-Event thread ( the one responsible for component painting ) .
The rest ( creating a new thread , creating a gui etc. ) is just scaffold code.
The output is like: