I have something like this:
for(int i=0; i<5; i++){
mytextarea.setText("hello " + i);
try{
Thread.currentThread().sleep(1000); //to give time for users to read
} catch(Exception e){}
}
I’m expecting it will display “hello 0” in the text area, wait for 1 second, then display “hello 1”, then wait for 1 second, etc.
But what happen is different, it waits for 5 seconds, then it displays “hello 4”.
Any idea?
Yes – you’re basically blocking the UI thread, so it’s never getting round to actually updating.
Sleeping in a UI thread is a really bad idea.
If you want to do something like this, you should use a
Timer. (I’m assuming you’re using Swing. If not, please edit your question to indicate which UI framework you’re using.)You should also note that
Thread.sleepis a static method. You’re using it as if it were an instance method. Admittedly you happen to be calling it “on” the current thread, but your usage suggest that you think that:would make the new thread sleep. It wouldn’t – it would make the current thread sleep, because that’s what
Thread.sleepalways does. IMO it was a mistake for Java to allow you to call static methods in this way – if you’re using Eclipse, there’s an option to make this a warning or error.