1

我正在开发一个 Java Swing 程序。如果我使用以下方法,会不会有一些性能下降?

jButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    SwingWorker worker = new SwingWorker() {
      protected Object doInBackground() throws Exception {
        return null;
      }

      protected void done() {
        // do stuff
      }
    };
    worker.execute();
  }
});

如果我在里面做一些繁重的处理任务,将实例定义为全局成员而不是本地匿名类声明done()会更好吗?SwingWorker

我认为如果它是本地的,那么每次actionPerformed调用时都会创建它(是吗?)。使用全局实例会提高性能吗?全局/本地方法的内存利用率有什么不同吗?

4

1 回答 1

4

In your specific example, it is very easy to answer. A SwingWorker is designed to be only run once, as specified in the class javadoc (see also this SO question)

SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice.

So in this case you will have to create a new instance each time the actionPerformed is invoked.

Side-note: the heavy processing work should be done in the doInBackground method, not in the done method or you will block the EDT

于 2013-08-18T11:51:17.210 回答