如何知道线程何时完成其任务

时间:2014-08-21 12:31:30

标签: java multithreading user-interface

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

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

但那不起作用。

任何人都可以帮助我

由于

4 个答案:

答案 0 :(得分:2)

一种选择是使用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) {
    }
  }
}

答案 1 :(得分:0)

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

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();

答案 2 :(得分:0)

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

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

然后,当每个Thread退出时,将使用刚刚完成的Thread实例调用您的notifyOfThreadComplete方法。现在,您可以在此方法中运行任何代码。

答案 3 :(得分:0)

使用Callable个帖子。它将返回值,因此我们可以确定它已完成任务。