我只是从我的教科书中学习一些例子,在Eclipse中编写代码来弄清楚它.
这是我有问题的方法的代码:
public void run() {
//Get the lock before entering the loop
synchronized(getClass()) {
for (int i =0; i<N; i++) {
System.out.println(getName() + " is tired");
try{
Thread.currentThread().sleep(DELAY);
} catch (InterruptedException e) {}
System.out.println(getName() + " is rested");
}
Run Code Online (Sandbox Code Playgroud)
在线上:
Thread.currentThread().sleep(DELAY)
Run Code Online (Sandbox Code Playgroud)
Eclipse给出了一个警告:"应该以静态方式访问Thread类型的静态方法sleep(long)".Eclipse建议使用以下解决方案:
Thread.currentThread();
Thread.sleep(DELAY);
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它会有所作为(如果确实如此).有人可以解释一下吗?:)
谢谢,
珍妮特
sleep()是一个静态方法,导致当前线程在指定的时间内休眠.因此,currentThread()调用是多余的,并且可能会让人感到困惑,因为它几乎意味着您可以通过使用类似的代码来使另一个线程休眠(您不能).
编写该代码的最佳方法是:
Thread.sleep(DELAY);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1835 次 |
| 最近记录: |