Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

user interface - Java: mytextarea.setText("hello") + Thread.sleep(1000) = strange result

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.sleep is 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:

Thread t = new Thread(...);
t.start();
t.sleep(1000);

would make the new thread sleep. It wouldn't - it would make the current thread sleep, because that's what Thread.sleep always 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...