Waiting for Multiple SwingWorkers
This question asks how to create multiple SwingWorkers, each responsible for updating a label, and remove all the labels when all workers have finished.
One solution is to employ a CountDownLatch, which allows a thread to wait for a specified number of other threads to complete their tasks before resuming execution. In the provided code, each worker invokes latch.countDown() on completion, while a Supervisor worker blocks on latch.await() until all tasks are finished. The Supervisor then updates the labels or removes them altogether (though the latter option is generally unappealing).
Here's an enhanced code example that demonstrates this approach:
import java.awt.Color; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.swing.*; /** * @see https://stackoverflow.com/a/11372932/230513 * @see https://stackoverflow.com/a/3588523/230513 */ public class WorkerLatchTest extends JApplet { private static final int N = 8; private static final Random rand = new Random(); private Queue<JLabel> labels = new LinkedList<JLabel>(); private JPanel panel = new JPanel(new GridLayout(0, 1)); private JButton startButton = new JButton(new StartAction("Do work")); public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame();
The above is the detailed content of How to Manage Multiple SwingWorkers and Update Labels Efficiently?. For more information, please follow other related articles on the PHP Chinese website!