Home > Java > javaTutorial > How to Manage Multiple SwingWorkers and Update Labels Efficiently?

How to Manage Multiple SwingWorkers and Update Labels Efficiently?

Susan Sarandon
Release: 2024-12-11 16:14:11
Original
277 people have browsed it

How to Manage Multiple SwingWorkers and Update Labels Efficiently?

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template