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

查看:113
本文介绍了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()。助手启动线程运行,我希望它在完成后知道,以便它可以返回被转换的对象。

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 has a method that does that for you. join will block until the thread has finished executing.

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

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