java – 等待多个SwingWorkers

前端之家收集整理的这篇文章主要介绍了java – 等待多个SwingWorkers前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请考虑以下代码片段:
  1. import java.awt.FlowLayout;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import java.lang.reflect.InvocationTargetException;
  5. import javax.swing.*;
  6.  
  7. public class TestApplet extends JApplet
  8. {
  9. @Override
  10. public void init()
  11. {
  12. try
  13. {
  14. SwingUtilities.invokeAndWait(new Runnable()
  15. {
  16. @Override
  17. public void run()
  18. {
  19. createGUI();
  20. }
  21. });
  22. }
  23. catch(InterruptedException | InvocationTargetException ex)
  24. {
  25. }
  26. }
  27.  
  28. private void createGUI()
  29. {
  30. getContentPane().setLayout(new FlowLayout());
  31. JButton startButton = new JButton("Do work");
  32. startButton.addActionListener(new ActionListener()
  33. {
  34. @Override
  35. public void actionPerformed(ActionEvent ae)
  36. {
  37. JLabel label = new JLabel();
  38. new Worker(label).execute();
  39. }
  40. });
  41. getContentPane().add(startButton);
  42. }
  43.  
  44. private class Worker extends SwingWorker<Void,Void>
  45. {
  46. JLabel label;
  47.  
  48. public Worker(JLabel label)
  49. {
  50. this.label = label;
  51. }
  52.  
  53. @Override
  54. protected Void doInBackground() throws Exception
  55. {
  56. // do work
  57. return null;
  58. }
  59.  
  60. @Override
  61. protected void done()
  62. {
  63. getContentPane().remove(label);
  64. getContentPane().revalidate();
  65. }
  66. }
  67. }

这是向applet添加一个标签,显示Worker线程的一些中间结果(使用publish / process方法).最后,标签从小应用程序的窗格中删除.我的问题是,我如何创建几个标签,每个标签都有自己的工作线程,并在完成后删除它们?

提前致谢.

更新:

我希望这将澄清我的问题.当所有的工作人员都完成了任务,而不是在每个工作人员完成后立即将标签全部删除.

更新2:

以下代码似乎正在做我需要的.请评论我是否做了正确的方法.我有一种感觉有什么问题.一个问题是,除去删除按钮之后,按钮右侧的标签仍然可见. setVisible(false)似乎解决了这个问题.是这样做吗?

  1. import java.awt.FlowLayout;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.util.LinkedList;
  6. import java.util.List;
  7. import java.util.Queue;
  8. import java.util.Random;
  9. import java.util.concurrent.ExecutorService;
  10. import java.util.concurrent.Executors;
  11. import javax.swing.*;
  12.  
  13. public class TestApplet extends JApplet
  14. {
  15. private Queue<JLabel> labels = new LinkedList<>();
  16. private static final Random rand = new Random();
  17.  
  18. @Override
  19. public void init()
  20. {
  21. try
  22. {
  23. SwingUtilities.invokeAndWait(new Runnable()
  24. {
  25. @Override
  26. public void run()
  27. {
  28. createGUI();
  29. }
  30. });
  31. }
  32. catch(InterruptedException | InvocationTargetException ex){}
  33. }
  34.  
  35. private void createGUI()
  36. {
  37. getContentPane().setLayout(new FlowLayout());
  38. JButton startButton = new JButton("Do work");
  39. startButton.addActionListener(new ActionListener()
  40. {
  41. @Override
  42. public void actionPerformed(ActionEvent ae)
  43. {
  44. ExecutorService executor = Executors.newFixedThreadPool(10);
  45. for(int i = 0; i < 10; i++)
  46. {
  47. JLabel label = new JLabel();
  48. getContentPane().add(label);
  49. executor.execute(new Counter(label));
  50. }
  51. }
  52. });
  53. getContentPane().add(startButton);
  54. }
  55.  
  56. private class Counter extends SwingWorker<Void,Integer>
  57. {
  58. private JLabel label;
  59.  
  60. public Counter(JLabel label)
  61. {
  62. this.label = label;
  63. }
  64.  
  65. @Override
  66. protected Void doInBackground() throws Exception
  67. {
  68. for(int i = 1; i <= 100; i++)
  69. {
  70. publish(i);
  71. Thread.sleep(rand.nextInt(80));
  72. }
  73.  
  74. return null;
  75. }
  76.  
  77. @Override
  78. protected void process(List<Integer> values)
  79. {
  80. label.setText(values.get(values.size() - 1).toString());
  81. }
  82.  
  83. @Override
  84. protected void done()
  85. {
  86. labels.add(label);
  87.  
  88. if(labels.size() == 10)
  89. {
  90. while(!labels.isEmpty())
  91. getContentPane().remove(labels.poll());
  92.  
  93. getContentPane().revalidate();
  94. }
  95. }
  96. }
  97. }

解决方法

I intend to remove all of the labels together when all of the workers have completed their tasks.

here所述,CountDownLatch在此上下文中工作良好.在下面的示例中,每个工作人员在完成时调用latch.countDown(),并且Supervisor工作程序阻塞latch.await(),直到所有任务完成.为了演示目的,主管更新标签.批评删除,在评论显示,在技术上是可能的,但通常没有吸引力.相反,请考虑一个JList或JTable.

  1. import java.awt.Color;
  2. import java.awt.EventQueue;
  3. import java.awt.GridLayout;
  4. import java.awt.event.ActionEvent;
  5. import java.util.LinkedList;
  6. import java.util.List;
  7. import java.util.Queue;
  8. import java.util.Random;
  9. import java.util.concurrent.CountDownLatch;
  10. import java.util.concurrent.ExecutorService;
  11. import java.util.concurrent.Executors;
  12. import javax.swing.*;
  13.  
  14. /**
  15. * @see https://stackoverflow.com/a/11372932/230513
  16. * @see https://stackoverflow.com/a/3588523/230513
  17. */
  18. public class WorkerLatchTest extends JApplet {
  19.  
  20. private static final int N = 8;
  21. private static final Random rand = new Random();
  22. private Queue<JLabel> labels = new LinkedList<JLabel>();
  23. private JPanel panel = new JPanel(new GridLayout(0,1));
  24. private JButton startButton = new JButton(new StartAction("Do work"));
  25.  
  26. public static void main(String[] args) {
  27. EventQueue.invokeLater(new Runnable() {
  28.  
  29. @Override
  30. public void run() {
  31. JFrame frame = new JFrame();
  32. frame.setTitle("Test");
  33. frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
  34. frame.add(new WorkerLatchTest().createGUI());
  35. frame.pack();
  36. frame.setLocationRelativeTo(null);
  37. frame.setVisible(true);
  38. }
  39. });
  40. }
  41.  
  42. @Override
  43. public void init() {
  44. EventQueue.invokeLater(new Runnable() {
  45.  
  46. @Override
  47. public void run() {
  48. add(new WorkerLatchTest().createGUI());
  49. }
  50. });
  51. }
  52.  
  53. private JPanel createGUI() {
  54. for (int i = 0; i < N; i++) {
  55. JLabel label = new JLabel("0",JLabel.CENTER);
  56. label.setOpaque(true);
  57. panel.add(label);
  58. labels.add(label);
  59. }
  60. panel.add(startButton);
  61. return panel;
  62. }
  63.  
  64. private class StartAction extends AbstractAction {
  65.  
  66. private StartAction(String name) {
  67. super(name);
  68. }
  69.  
  70. @Override
  71. public void actionPerformed(ActionEvent e) {
  72. startButton.setEnabled(false);
  73. CountDownLatch latch = new CountDownLatch(N);
  74. ExecutorService executor = Executors.newFixedThreadPool(N);
  75. for (JLabel label : labels) {
  76. label.setBackground(Color.white);
  77. executor.execute(new Counter(label,latch));
  78. }
  79. new Supervisor(latch).execute();
  80. }
  81. }
  82.  
  83. private class Supervisor extends SwingWorker<Void,Void> {
  84.  
  85. CountDownLatch latch;
  86.  
  87. public Supervisor(CountDownLatch latch) {
  88. this.latch = latch;
  89. }
  90.  
  91. @Override
  92. protected Void doInBackground() throws Exception {
  93. latch.await();
  94. return null;
  95. }
  96.  
  97. @Override
  98. protected void done() {
  99. for (JLabel label : labels) {
  100. label.setText("Fin!");
  101. label.setBackground(Color.lightGray);
  102. }
  103. startButton.setEnabled(true);
  104. //panel.removeAll(); panel.revalidate(); panel.repaint();
  105. }
  106. }
  107.  
  108. private static class Counter extends SwingWorker<Void,Integer> {
  109.  
  110. private JLabel label;
  111. CountDownLatch latch;
  112.  
  113. public Counter(JLabel label,CountDownLatch latch) {
  114. this.label = label;
  115. this.latch = latch;
  116. }
  117.  
  118. @Override
  119. protected Void doInBackground() throws Exception {
  120. int latency = rand.nextInt(42) + 10;
  121. for (int i = 1; i <= 100; i++) {
  122. publish(i);
  123. Thread.sleep(latency);
  124. }
  125. return null;
  126. }
  127.  
  128. @Override
  129. protected void process(List<Integer> values) {
  130. label.setText(values.get(values.size() - 1).toString());
  131. }
  132.  
  133. @Override
  134. protected void done() {
  135. label.setBackground(Color.green);
  136. latch.countDown();
  137. }
  138. }
  139. }

猜你在找的Java相关文章