简体   繁体   English

等待线程在Java中完成

[英]Wait for thread to finish in Java

I have some code which executes a download in a separate thread, created so that the JFrame GUI will continue to update during the download. 我有一些代码在一个单独的线程中执行下载,创建后JFrame GUI将在下载过程中继续更新。 But, the purpose is completely defeated when I use Thread.join(), as it causes the GUI to stop updating. 但是,当我使用Thread.join()时,目的完全失败,因为它导致GUI停止更新。 I need a way to wait for the thread to finish and still update the GUI. 我需要一种方法来等待线程完成并仍然更新GUI。

You can have the task that does the download also fire an event to the GUI. 您可以让执行下载的任务也向GUI发出事件。

For example: 例如:

Runnable task = new Runnable() {
   public void run() {
      // do your download

      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            // call some method to tell the GUI that the download finished.
         }
      });
   }
};

and then to run it, either use an Executor (preferred method) or a raw thread: 然后运行它,使用Executor (首选方法)或原始线程:

executor.execute(task);

or 要么

new Thread(task).start();

As pointed out in the comments, you'd generally use a SwingWorker to do this kind of thing but you can also do the manual approach outlined above. 正如评论中指出的那样,您通常使用SwingWorker来执行此类操作,但您也可以执行上面概述的手动方法。

SwingWorker provides a doInBackground method where you would stick your download logic in, a done method where you would stick in code to notify the GUI that the download finished and a get method to get the result of doInBackground (if there was one). SwingWorker提供了一个doInBackground方法,您可以在其中使用下载逻辑,这done一种done方法,您可以在其中使用代码来通知GUI下载完成,以及get doInBackground结果的get方法(如果有的话)。

Eg, 例如,

class Downloader extends SwingWorker<Object, Object> {
   @Override
   public Object doInBackground() {
       return doDownload();
   }

   @Override
   protected void done() {
       try { 
         frame.downloadDone(get());
       } catch (Exception ignore) {
       }
   }
}

(new Downloader()).execute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM