Java: mytextarea.setText(“hello”) + Thread.sleep(1000) = strange result

前端 未结 4 1606
清歌不尽
清歌不尽 2020-12-21 11:20

I have something like this:

for(int i=0; i<5; i++){
    mytextarea.setText(\"hello \" + i);
    try{
        Thread.currentThread().sleep(1000); //to give         


        
4条回答
  •  一整个雨季
    2020-12-21 11:58

    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.

提交回复
热议问题