考慮以下程式碼片段:
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import javax.swing.*; public class TestApplet extends JApplet { @Override public void init() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { createGUI(); } }); } catch(InterruptedException | InvocationTargetException ex) { } } private void createGUI() { getContentPane().setLayout(new FlowLayout()); JButton startButton = new JButton("Do work"); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { JLabel label = new JLabel(); new Worker(label).execute(); } }); getContentPane().add(startButton); } private class Worker extends SwingWorker<Void, Void> { JLabel label; public Worker(JLabel label) { this.label = label; } @Override protected Void doInBackground() throws Exception { // do work return null; } @Override protected void done() { getContentPane().remove(label); getContentPane().revalidate(); } } }
這裡的目標是加入小程式的標籤,顯示工作線程的一些中間結果(使用發布/處理方法)。最後,標籤將從小程式的窗格中刪除。問題是,如何創建多個標籤,每個標籤都有自己的工作線程,並在它們全部完成後將其刪除?
CountDownLatch 在這種情況下效果很好。在下面的範例中,每個工作執行緒在完成時呼叫latch.countDown(),而Supervisor工作執行緒阻塞在latch.await()上,直到所有任務完成。出於演示目的,主管更新了標籤。評論中顯示的批量刪除在技術上是可行的,但通常沒有吸引力。相反,請考慮 JList 或 JTable。
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();
以上是如何在 JApplet 中管理多個 SwingWorker 執行緒及其關聯標籤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!