java Thread.currentThread().sleep(time) v/s Thread.sleep(time);
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3325942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Thread.currentThread().sleep(time) v/s Thread.sleep(time);
提问by Jazz
Possible Duplicate:
Java: Thread.currentThread().sleep(x) vs. Thread.sleep(x)
可能的重复:
Java:Thread.currentThread().sleep(x) 与 Thread.sleep(x)
whats the difference between...
有什么区别...
Thread.currentThread().sleep(time)
and
和
Thread.sleep(time);
one more thing is there anyother method by which i can delay in program without using Thread Class...
还有一件事是我可以在不使用线程类的情况下延迟程序的任何其他方法......
回答by Tim Bender
Thread.sleep()is a static method. There is no difference between calling Thread.sleep()and calling Thread.currentThread().sleep(). However, if you use eclipse, the latter form should give you a warning message as you are accessing the static method sleep() in a non-static way.
Thread.sleep()是一个静态方法。callThread.sleep()和 call之间没有区别Thread.currentThread().sleep()。但是,如果您使用 eclipse,当您以非静态方式访问静态方法 sleep() 时,后一种形式应该会给您一条警告消息。
TimeUnit.sleep()is a fantastic alternative to Thread.sleep(). I personally prefer it because in most cases I want to sleep for whole seconds and I can easily and clearly do this with TimeUnit.SECONDS.sleep(5)as opposed to Thread.sleep(5*1000)or Thread.sleep(5000)
TimeUnit.sleep()是 Thread.sleep() 的绝佳替代品。我个人比较喜欢它,因为在大多数情况下,我要睡了整个秒,我可以很容易和清楚地做到这一点用TimeUnit.SECONDS.sleep(5),而不是Thread.sleep(5*1000)或Thread.sleep(5000)
Edit:There is yet another alternative, but it is not at all a desirable alternative. Calling Object.wait()will halt execution in a similar fashion to Thread.sleep(). However, it is inadvisable to do so because first you have to use synchronize(Object)and this method is intended for wait/notify Thread synchronization. Also, there is no guarantee that the Thread will wait for the full time specified as spurious wake-ups from Object.wait() are acceptable for JVM implementations.
编辑:还有另一种选择,但它根本不是理想的选择。调用Object.wait()将以类似于 Thread.sleep() 的方式停止执行。但是,这样做是不可取的,因为首先您必须使用synchronize(Object)并且此方法用于等待/通知线程同步。此外,也不能保证线程将等待指定的全部时间,因为 Object.wait() 的虚假唤醒对于 JVM 实现是可以接受的。
回答by mhshams
1 - they are same.
1 - 他们是一样的。
2 - Thread.sleep is the only way to delay in Java unless you implements your own way ;)
2 - Thread.sleep 是在 Java 中延迟的唯一方法,除非您实现自己的方式;)

