1

我有两个线程。一个是从我的 BulkProcessor 类运行业务逻辑,该类更新 BulkProcessor.getPercentComplete() 变量:

public void run(){
   new SwingWorker<Void,Void>() {
      protected Void doInBackground() throws Exception {
         BulkProcessor.main(jTextField0.getText(), jTextField1.getText());
         return null;
      };
   }.execute();
}

我的另一个线程是在我的 BulkGUI 类中更新 jProgressBar 的值:

public void update(){
   jProgressBar0.setStringPainted(true);
   jProgressBar0.repaint();
   new SwingWorker<Void,Integer>() {
   protected Void doInBackground() throws Exception {
      do
      {
          percentComplete = BulkProcessor.getPercentComplete();
          publish(percentComplete);
          Thread.sleep(100);
      } while(percentComplete < 100);
      return null;
      } 
      @Override
      protected
      void process(List<Integer> progress)
      {
          jProgressBar0.setValue(progress.get(0));
      }
}.execute();
}

单击“进程”按钮时,我调用了两个线程:

private void jButton0ActionActionPerformed(ActionEvent event) {
run();
update();
}

第一次运行它完全符合预期。但是再次选择 Process 按钮对 jProgressBar 没有影响。更新线程中的局部变量 percentComplete 保持在 100,并且不会像第一次运行那样更新。我测试了 BulkProcessor 类中的 percentComplete 变量,这个变量实际上按预期更新。因此,由于某种原因,线程在第二次调用线程时没有使用 BulkProcessor.getPercentComplete() 获取更新值。有人对此有任何见解吗?任何帮助深表感谢。

4

2 回答 2

2

我猜你的问题很可能是因为百分比完成是你第二次按下按钮时的最大值。建议:

  • 每次运行代码时重置 percentComplete。
  • 避免从后台线程中进行 Swing 调用,包括读取文本字段文本。
  • 而是在 SwingWorker 的构造函数中执行此操作,而不是在其doInBackground(...)方法中。
  • 您似乎正在进行静态字段和/或方法调用。如果是这样,不要因为这最终会咬你,而是创建并传递有效的引用。
  • 我猜要做到这一点,你会想要创建一个新的 BulkProcessor 对象。
  • 调用run(),然后update()像你正在做的那样,让两个线程同时运行对我来说看起来很危险,这可能是为竞争条件设置的。

编辑

您应该考虑将 SwingWorker 的进度属性与 PropertyChangeListener 一起使用。例如:

public class FooGUI {

   // .....

   public void myRun() {
      String text1 = someTextField.getText();
      String text2 = otherTextField.getText();
      final BulkProcessor bulkProcessor = new BulkProcessor(text1, text2);
      bulkProcessor.addPropertyChangeListener(new PropertyChangeListener() {

         @Override
         public void propertyChange(PropertyChangeEvent pcEvt) {
            if (pcEvt.getPropertyName().equals("progress")) {
               int progress = bulkProcessor.getProgress();
               someProgressBar.setValue(progress);
            }
         }
      });
   }
}

class BulkProcessor extends SwingWorker<Void, Void> {
   private Random random = new Random(); // just for SSCCE sake
   private String text1;
   private String text2;

   public BulkProcessor(String text1, String text2) {
      this.text1 = text1;
      this.text2 = text2;
      // not sure what you do with these texts....
   }

   @Override
   protected Void doInBackground() throws Exception {
      int progress = 0;
      while (progress <= 100) {
         progress = random.nextInt(5); // just as a for instance
                                    // your code will do something else of course
         setProgress(progress);
         Thread.sleep(300);
      }
      return null;
   }

}

例如:

import java.awt.event.*;
import java.beans.*;
import java.util.Random;
import javax.swing.*;

@SuppressWarnings("serial")
public class Foo3 extends JPanel {
   private static final String DEFAULT_SPEED = "15";
   private JTextField speedTextField = new JTextField(DEFAULT_SPEED, 5);
   private JProgressBar someProgressBar = new JProgressBar();
   private RunAction runAction = new RunAction();
   private JButton runButton = new JButton(runAction);

   public Foo3() {
      speedTextField.setAction(runAction);

      add(new JLabel("Speed:"));
      add(speedTextField);
      add(someProgressBar);
      add(runButton);
   }

   public void myRun() {
      String speedText = speedTextField.getText();
      try {
         int speed = Integer.parseInt(speedText);
         final BulkProcessor bulkProcessor = new BulkProcessor(speed);
         bulkProcessor.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent pcEvt) {
               if (pcEvt.getPropertyName().equals("progress")) {
                  int progress = bulkProcessor.getProgress();
                  someProgressBar.setValue(progress);
               }
               if (pcEvt.getPropertyName().equals("state")) {
                  if (bulkProcessor.getState().equals(
                        SwingWorker.StateValue.DONE)) {
                     someProgressBar.setValue(0);
                     setGuiEnabled(true);
                  }
               }
            }
         });
         setGuiEnabled(false);
         bulkProcessor.execute();
      } catch (NumberFormatException e) {
         String text = "Speed of " + speedTextField.getText()
               + " is invalid. Please enter an integer";

         JOptionPane.showMessageDialog(this, text, "Invalid Speed Value",
               JOptionPane.ERROR_MESSAGE);
         speedTextField.setText(DEFAULT_SPEED);
      }
   }

   private class RunAction extends AbstractAction {
      public RunAction() {
         super("Run");
         putValue(MNEMONIC_KEY, KeyEvent.VK_R);
      }

      @Override
      public void actionPerformed(ActionEvent arg0) {
         myRun();
      }

   }

   private void setGuiEnabled(boolean enabled) {
      runButton.setEnabled(enabled);
      speedTextField.setEnabled(enabled);
   }

   private static void createAndShowGui() {
      Foo3 mainPanel = new Foo3();

      JFrame frame = new JFrame("Foo3");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class BulkProcessor extends SwingWorker<Void, Void> {
   private Random random = new Random(); // just for SSCCE sake
   private int speed;

   public BulkProcessor(int speed) {
      this.speed = speed;
   }

   @Override
   protected Void doInBackground() throws Exception {
      int progress = 0;
      while (progress <= 100) {
         progress += random.nextInt(speed);
         setProgress(progress);
         Thread.sleep(300);
      }
      return null;
   }

}
于 2013-09-10T14:38:46.387 回答
0

因此发现将 while(percentComplete < 100) 更改为 while(percentComplete <= 100) 可以使线程永久运行。这实际上解决了问题,但可能不推荐。

于 2013-09-10T15:01:20.990 回答