静态休眠线程与使用其实例
-
Thread workerThread = new Thread(runnable);
workerThread.start();
workerThread.sleep(5000);
.....
它们都会
Thread workerThread = new Thread(runnable);
workerThread.start();
Thread.sleep(5000);
导致工作线程暂停睡眠吗?
谢谢
What is the difference between -
Thread workerThread = new Thread(runnable);
workerThread.start();
workerThread.sleep(5000);
.....
And
Thread workerThread = new Thread(runnable);
workerThread.start();
Thread.sleep(5000);
Do they both cause worker thread to pause sleep?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
否 sleep 是影响当前线程的静态方法: http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#sleep(long)
所以没有区别在于,他们都不会做你想做的事。不建议在实例上使用静态方法,
不推荐,因为它会让您认为您可以做一些实际上做不到的事情(就像在本例中一样)小补充 - 请参阅 John 对 为什么调用静态Java 中允许使用类实例的方法
:-)
No sleep is a static method that affects the current thread: http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#sleep(long)
So there is no difference, they both won't do what you want. The use of static methods on an instance is
deprecateddiscouraged since it make you think you can do something you actually can't (like in this case)Small addition - see John's answer to why calling static methods from class instances is allowed in Java
:-)
两个实例中的
sleep
是相同的静态方法,它会导致当前正在执行的线程休眠,而不是工作线程休眠。sleep
in both instances is the same static method that would cause the currently executing thread to sleep, not the workerThread.唯一实际的调用是
另一个是java的奇怪之处,你可以通过实例变量调用静态方法。
您应该始终使用
它,因为它是更好的自记录,它是当前线程“始终”正在休眠。如果您这样做,
则您不是在休眠 myThread 线程,而是在休眠当前线程。
The only actual call is
The other is an oddity of java that you can call static method's through instance variables.
You should always use
As it is better self-documenting that it is the current thread 'always' that is being slept on. If you do
You are not sleeping the myThread thread, you are sleeping the current thread.
第二个方法应该是首选,因为 Thread.sleep 是一个静态方法,因此应该像所有静态方法一样,始终在定义它的类上而不是在此类的实例上调用。
The second one should be preferred, because Thread.sleep is a static method, and should thus always be invoked, like all static methods, on the class defining it rather than on an instance of this class.
这是另一种可能性。使用易失性标志将消息传递给 C。
这不是真正的代码,足以让您了解我的意思。例如,您需要注意 startC 标志的可见性,或者为其编写一个公共 getter 和 setter,以便 B() 和 C() 都可以访问。
Here is another possibility. Use a volatile flag to pass the message to C.
This is not real code, just enough to give you the idea of what I am getting at. For example, you will need to pay attention to the visibility of the startC flag, or write a public getter and setter for it so B() and C() both have access.