簡體   English   中英

如何知道線程何時完成其任務

[英]How to know when a thread has completed its task

當我使用gui時,我需要創建一個線程來完成任務。 請參閱我想顯示一個對話框,讓用戶知道我嘗試過的任務已完成

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

但這不起作用。

誰能幫我

謝謝

一種選擇是使用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) {
    }
  }
}

您可以讓線程在運行方法中的最后一行代碼中顯示一條消息:

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

在主線程中創建一個偵聽器,然后對線程進行編程以告知偵聽器它已完成。

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實例調用您的notifyOfThreadComplete方法。 因此,現在您可以使用此方法運行任何代碼。

使用Callable線程。 它將返回值,因此我們可以確定它已完成任務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM