I have made a swings application but there is one problem in that which is as follow:
I have initiated a SwingWorker thread named “Thread-Main” from the Event Dispatch Thread and have passed a JLabel reference of the GUI to the “Thread-Main”.
Now I have started 10 threads from the “Thread-Main”.
Now I want that all the 10 threads should update the JLabel.
How can I do that?
Someone told me that I can do this by first making all the 10 threads subclasses of SwingWorker and then calling the publish(“”) method and passing the string in that “publish” method and then collecting all the published strings by the following method in “Thread-Main”
@Override
protected void process(List<String> labelStrings) {
String count = labelStrings.get(labelStrings.size() - 1);
label.setText(count); // label is a reference to a label in the GUI
}
- Is the above approach is correct to do that?
- Should the 10 threads be subclasses of SwingWorker?
- Is there any other way to do that?
SwingWorkercode you’ll see that it uses aThreadPoolExecutorinternally containing a maximum of 10 threads. If you kick off a number ofSwingWorker‘s concurrently they will all run using this executor. However, you have no direct control over whether the background threads are executed in parallel.My recommended solution would be:
SwingWorker.doInBackground()method kick off 10 threads either directly or by using anExecutorService.CountDownLatchorCompletionServiceto synchronize between your master thread (i.e.SwingWorkerbackground thread) and worker threads.Example
Define the number of worker threads to invoke and declare the JLabel to be updated.
Define the unit of work we wish to execute as a
Callable<String>. TheStringresult will be used to update theJLabel.Now kick off a
SwingWorker, which will in turn kick off multiple parallel workers to do any processing. The worker will not return a result via the call todone()(hence theVoidtype) but will marshall intermediateStringresults back onto the Swing thread by callingprocess(String... chunks).Define
doInBackground()to kick off the worker threads and block for each result using aCompletionService.Now we implement
process(String... chunks)to simply update theJLabelwhen called.Finally we override
done()to marshall any exceptions back onto the Swing thread.