Java 等待线程完成 [英] Java Wait for thread to finish

查看:32
本文介绍了Java 等待线程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程正在下载数据,我想等到下载完成后再加载数据.有没有标准的方法来做到这一点?

I have a thread downloading data and I want to wait until the download is finished before I load the data. Is there a standard way of doing this?

更多信息:

我有一个从 URL(序列化 POJO)获取数据的下载类.下载是可运行和可观察的.它跟踪下载的字节数和下载大小.我有一个进度条,向用户显示进度.GUI 观察下载以更新进度条.

I have a Download class that gets data from a URL (Serialized POJOs). Download is Runnable and Observable. It keeps track of the bytes downloaded and download size. I have a progress bar that displays the progress to the User. The GUI observes Download to update the progress bar.

下载 POJO 后,我想获取它并进行下一步.每一步都必须等待前一步完成.问题是我想不出一种方法来暂停我的应用程序以等待下载线程.下载完成后,我想调用 download.getObject() 它将数据作为对象返回.然后我可以投射它并继续进行下一次下载.

When the POJO is downloaded I want to get it and move to the next step. Each step has to wait for the previous to finish. The problem is I cant think of a way to pause my application to wait for the download thread. Once the download is finished I want to call download.getObject() which will return the data as an object. I can then cast it and get on with the next download.

我有一个帮助程序类,用于管理下载的 URL 并进行所有对下载的调用.此调用将调用 getObject 并进行转换.Gui 调用 helper.getUser().helper 启动线程运行,我希望它知道"何时完成,以便它可以返回投射的对象.

I have a helper class that manages the URLs for download and makes all of the calls to Download. This call will call getObject and do the casting. The Gui calls helper.getUser(). helper starts the thread running and I want it to 'know' when it is finished so it can return the casted object.

有什么建议/例子吗?我正处于这个设计的开始阶段,所以我愿意改变它.

Any suggestions/examples? I am in the beginning stages of this design so I am willing to change it.

更新:

我关注了http:///download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html#get 并使用模态阻塞直到线程完成.代码很乱,我不喜欢这种方法.我将继续努力寻找一种干净"的方式来处理下载过程的工作流程.

I followed http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html#get and used modal to block until the thread finished. The code was very messy and I don't like this approach. I will keep trying to find a 'clean' way to handle the workflow of the download processes.

推荐答案

Thread 有一个方法可以为您做到这一点join 它将阻塞直到线程完成执行.

Thread has a method that does that for you join which will block until the thread has finished executing.

这篇关于Java 等待线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆