【问题标题】:How to know when a thread has completed its task如何知道线程何时完成其任务
【发布时间】:2014-08-21 12:31:29
【问题描述】:

当我使用 gui 时,我需要创建一个线程来完成任务。请参阅我想显示一个对话框,让用户知道我尝试过的任务已完成

if(!thread.isAlive()) {
    JOptionPane.showMessageDialog(null, "Done");
}

但这不起作用。

谁能帮帮我

谢谢

【问题讨论】:

  • 你想让你的主线程等待另一个线程完成吗?
  • 让线程告诉你,或者让它显示对话框本身。不要将这样的代码放入事件线程中。

标签: java multithreading user-interface


【解决方案1】:

一种选择是使用SwingWorker 完成您的工作。覆盖 done() 方法并让它通知您的 GUI 工作已完成。

页面顶部的 Javadocs 中显示了一个与您的用例几乎匹配的简单示例:

final JLabel label;
class MeaningOfLifeFinder extends SwingWorker<String, Object> {
  @Override
  public String doInBackground() {
    // Here you do the work of your thread
    return findTheMeaningOfLife();
  }

  @Override
  protected void done() {
    // Here you notify the GUI
    try {
      label.setText(get());
    } catch (Exception ignore) {
    }
  }
}

【讨论】:

    【解决方案2】:

    你可以让线程打印一条消息,因为它是它的 run 方法中的最后一行代码:

    Thread thread = new Thread() {
      @Override
      public void run() {
          //whatever you want this thread to do
    
          //as the last line of code = the thread is going to terminate
          JOptionPane.showMessageDialog(null, "Done"); 
      }
    }
    thread.start();
    

    如果您希望主线程等待线程完成,请在您使用的主线程代码中:

    thread.join();
    

    【讨论】:

      【解决方案3】:

      在您的主线程中创建一个侦听器,然后对您的线程进行编程以告诉侦听器它已完成。

      public interface ThreadCompleteListener {
          void notifyOfThreadComplete(final Thread thread);
      }
      

      然后创建以下类:

      public abstract class NotifyingThread extends Thread {
        private final Set<ThreadCompleteListener> listeners
                         = new CopyOnWriteArraySet<ThreadCompleteListener>();
        public final void addListener(final ThreadCompleteListener listener) {
          listeners.add(listener);
        }
        public final void removeListener(final ThreadCompleteListener listener) {
          listeners.remove(listener);
        }
        private final void notifyListeners() {
          for (ThreadCompleteListener listener : listeners) {
            listener.notifyOfThreadComplete(this);
          }
        }
        @Override
        public final void run() {
          try {
            doRun();
          } finally {
            notifyListeners();
          }
        }
        public abstract void doRun();
      }
      
      NotifyingThread thread1 = new OneOfYourThreads();
      thread1.addListener(this); // add ourselves as a listener
      thread1.start();           // Start the Thread
      

      然后,当每个线程退出时,您的notifyOfThreadComplete 方法将被刚刚完成的线程实例调用。所以现在你可以在这个方法中运行你的任何代码了。

      【讨论】:

        【解决方案4】:

        使用Callable 线程。它将返回值,因此我们可以确定它完成了任务。

        【讨论】:

          猜你喜欢
          • 2013-11-08
          • 2012-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-02
          • 1970-01-01
          • 2011-03-07
          • 1970-01-01
          相关资源
          最近更新 更多