线程和闪屏
我有一个应用程序,它依赖于在向用户呈现 GUI 之前从 N 个文件创建某些对象。我决定创建一个启动屏幕,并希望显示一个进度条,以估计应用程序初始任务的进度。
我刚刚开始研究 java.util.concurrent API,并正在考虑使用 CountDownLatch 和 FutureTask 来解决这个问题:为每个需要读取的文件创建一个 FutureTask 并获取构造的对象;使用 CountDownLatch 来确保在初步任务完成之前不会显示 GUI,并记录我们在进程中的进度(通过查询 getCount() 并相应地在启动屏幕的图像上重新绘制状态栏。
这是多余的吗?
I have an application that relies on the creation of certain objects from N files before a GUI should be presented to the user. I have decided to create a splash screen and want to show a progress bar giving an estimate of how far the app has progressed with its initial tasks.
I have just started studying the java.util.concurrent API and am thinking of solving this by using CountDownLatch and FutureTask: Create a FutureTask for each of the files needed to be read and get the constructed objects; use the CountDownLatch to both ensure the GUI is not presented until preliminary tasks are done and to register how far in the process we are (by querying getCount() and redraw a status bar over the image of the splash screen accordingly.
Is this overkill ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
信号量 是更好,因为您可以允许在启动期间重用任务的线程,
使用 s = new Semaphore(-nbFiles+1) 创建信号量,并让每个任务在启动时调用 s.release()完成文件后,
启动屏幕可以通过 nbFiles+s.availablePermits() 知道一切进展到什么程度
a semaphore is better as you can allow the threads of the tasks to be reused during startup
create the semaphore with
s = new Semaphore(-nbFiles+1)
and have each task call s.release() when they are done with a filethe splash screen can know how far everything is progressed with nbFiles+s.availablePermits()
我将创建一个 CountDownLatch 这是使用显示 UI 之前需要执行的任务数进行初始化。
然后我会使用例如 固定线程池,我向其中发布类似于以下内容的任务:
监视线程(注意这不应由 UI 线程执行)应该执行如下操作:
注意,代码未经测试,可能无法编译,但是它说明了您想要做什么。
I would create a CountDownLatch that is initialized with the number of tasks that you need to execute before you can display the UI.
I would then use e.g a fixed thread pool to which I post tasks similar to:
The monitoring thread (note this should not be executed by the UI thread) should do something like this:
Note, the code isn't tested, and might not compile, but it illustrates what you want to do.