I am using SwingWorker to execute some heavy load tasks on an application I am making . Although today I got across the Executor class and this example :
Executors.newCachedThreadPool().execute(new Runnable() {
public void run() {
someTask();
});
Can someone explain the reasons why one would use SwingWorker instead of the above example ? This is the way I am currently using SwingWorker :
SwingWorker worker = new SwingWorker() {
protected Object doInBackground() {
someTask();
return null;
}
};
worker.execute();
1) SwingWorker
is created as bridge betweens Java Essentials Classes
and Swing by implements Future
, and quite guarantee that outoput from methods process
, publish
and done
will be on EventDispatchThread
2) you can invoke SwingWorker
from Executor
, this is most safiest methods how to create multithreading in Swing by implements SwingWorker
3) notice carefully with number or thread, because Executor
doesn't care somehow about SwingWorkers
life_cycle
4) another important notice and here
5) for listening states from SwingWorker
you have to implements PropertyChangeListener
The SwingWorker
has additional methods process()
and done()
which are automatically executed in the event dispatch thread. This comes in handy if you plan to display your progress or final results in a user interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With