Thread.Sleep() is freezing

后端 未结 3 668
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 08:30

Here is a snippet

kit.insertHTML(doc, doc.getLength(), \"Hello\", 0, 0, null);
try{
Thread.sleep(1000);
}catch(Exception e){}

I am using

相关标签:
3条回答
  • 2020-11-27 09:11

    Thread.sleep is a long running task. When you a running such a task in the EDT it blocks all repaint requests from being executed. All repaint requests which are pending and which were sent during the sleep phase are queued for future processing.

    As a result when the EDT comes out of the sleep phase it coalesce all such repaint request (if coalescing is enabled which is the default property) into a single repaint which gets executed. If coalescing is not enabled then all queued request are executed serially without any time gap in between. As a result it seems that the UI did not update.

    To correct the situation use a SwingTimer which triggers periodically after specific intervals of time, or a SwingWorker.

    0 讨论(0)
  • 2020-11-27 09:18

    Don't ever call Thread.sleep(...) from within the Swing event thread as this will put the event thread itself to sleep. Since this thread is responsible for all Swing painting and user interaction, this will put your application to sleep.

    If all you want is a delay in the display, then consider use of a Swing Timer.

    If on the other hand your event thread is being compromised by a long-running task, then do the task in the background, using a SwingWorker (as suggested by Guillaume 1+ to him).

    0 讨论(0)
  • 2020-11-27 09:28

    You are calling sleep on the EDT (Event Dispatching Thread). You should avoid this situation as indeed, it freezes the UI.

    To avoid this situation, use a SwingWorker instead or as suggested by HFOE, use a Swing Timer

    0 讨论(0)
提交回复
热议问题