Reputation: 179
I'm in the process of designing a Java GUI driven application that runs a number of separate tasks, each within its own SwingWorker extended class. This is the normal design I use in order to run tasks on their own threads and still keep the EDT free to update the GUI. Each SwingWorker is started on its own thread using an Executors.newCachedThreadPool.
However, within one particular class, there is a task that requires quite a long time to process. The task contains a for loop that performs some calculations up to six times.
I've had the thought of implementing each of the six calculations within their own thread to speed up processing time, but I'm not sure of the best way of implementing this.
Is it possible to both extend SwingWorker and implement Runnable, and then use a void Run() method within the for loop, starting a new Thread each time, or using a cachedThreadPool.
Or am I better off just using standard Thread() implementation?
Any advice or suggestions would be appreciated.
Thanks in advance
Josh
Upvotes: 8
Views: 4779
Reputation: 13608
user988052 is right of course - if you don't have a multi core CPU, doing the computation in six different threads will actually slow down your application because of the overhead that comes with the creation and administration of threads.
If you want to do this calculations in six separate threads nevertheless, you could use a SwingWorker as the managing thread and spawn off 5-6 new threads within it. Using ExecutorService
would then be the way to go, since it uses a pool of threads and thus minimizes the overhead that comes with the creation and disposal of a thread.
Edit: to answer your comment:
I think the best way would be the implement your calculation in a Runnable
(so that each of the six calculations can run separately), then simply use an ExecutorService
, instantiate your Runnable
six times and use ExecutorService.submit(Runnable task)
. You can do all of this within the SwingWorker.doInBackground()
method.
You should never call the run()
method yourself - let that be done by a Thread/ExecutorService.
Upvotes: 8