开发者

Threads and a splash screen

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() an开发者_运维知识库d redraw a status bar over the image of the splash screen accordingly.

Is this overkill ?


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 file

the splash screen can know how far everything is progressed with nbFiles+s.availablePermits()


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:

public class Task implements Runnable {
   CountDownLatch latch;
   public Task(CountDownLatch latch) {
      this.latch = latch;
   }

   public void run() {
      //First perform some business logic... then
      latch.countDown();
   }
}

The monitoring thread (note this should not be executed by the UI thread) should do something like this:

public void monitorProgress(final CountDownLatch latch) {
   while (latch.await(5, TimeUnit.SECONDS) == false) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            // update the progress, latch.getCount() tasks are remaining
         }
      });
   }
   //Execution has been completed once you reach this line..
}

Note, the code isn't tested, and might not compile, but it illustrates what you want to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜