简体   繁体   中英

Thread.join freezes progressbar

I have a code which uses a thread to run multiple progress bar.

Thread thread1 = new Thread(progressbar1);
thread1.start(); 
thread2.start()

And so on. After I have

thread1.join(); 
thread2.join(); 
thread3.join();

But that freezes all three progress bar animation and shows the completion only when all threads are done. How to solve this problem? Thanks.

Doing any blocking operation on the Event Dispatch Thread will cause your GUI to become unresponsive and stop being repainted. That's why long-running operations should be done in a background thread.

It seems like you know you need to do things in a background thread but still want to block the EDT. You shouldn't do that. Instead, you want a callback--some code that will be run once your background threads have finished running.

An already provided callback mechanism available in Java 6+ is SwingWorker . Implement a worker, putting the join() s (and start() s) in the doInBackground() method. Then any Swing operations that you want to do afterward can go in done() .

You're blocking the UI thread. You shouldn't do that. Options:

  • Have another thread which just calls join on the first three. Wasteful in terms of creating another resource, but reasonably straightforward.
  • Use a counter - making sure that you use something like AtomicInteger to ensure that you don't run into memory model and race condition issues. Start the counter at 3, and decrement it at the end of each thread When the last thread finishes its work (ie its decrement puts the counter to 0), make it call back into the UI.

(The second bullet may be what you were doing already... it's hard to tell for sure given the description of just "I used a counter.")

While I entirely see where you're coming from in terms of the control flow of the application being much harder in an event-driven world, that's the way Swing works (and it's the way most other UI frameworks work, too). You simply can't block the UI thread. (This is also why C# 5 is making it all easier at the language level...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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