问题描述
我有这样的事情:
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){}
}
我希望它会在文本区显示hello 0,等待1秒,然后显示hello 1,然后等待1秒等等。
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.
但是发生了什么不同,等待5秒,然后显示你好4。
But what happen is different, it waits for 5 seconds, then it displays "hello 4".
有什么想法吗?
推荐答案
是的 - 你基本上阻止了UI线程,所以它永远不会实际更新。
Yes - you're basically blocking the UI thread, so it's never getting round to actually updating.
在UI线程中睡觉是一个非常糟糕的主意。
如果你想做这样的事情,你应该使用。 (我假设您正在使用Swing。如果没有,请编辑您的问题以指明您正在使用的UI框架。)
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.)
您还应注意 Thread.sleep
是一种静态方法。您正在使用它,就好像它是一个实例方法。诚然,你碰巧在当前线程上打电话,但你的用法表明你认为:
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);
会使 new 线程休眠。它不会 - 它会使当前线程休眠,因为那是 Thread.sleep
总是。 IMO让Java以这种方式调用静态方法是错误的 - 如果你正在使用Eclipse,那么可以选择将其作为警告或错误。
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.
这篇关于Java:mytextarea.setText(" hello")+ Thread.sleep(1000)=奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!