在下面的代码中,编译器建议我使用Thread.sleep(静态引用)而不是this.sleep,为什么会这样?
public class CThreadUsingThread extends Thread{
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println("Thread running:"+i);
try {
// Why Thread.sleep(Math.round(Math.random()*1000)); is preferred?
this.sleep(Math.round(Math.random()*1000));
} catch (InterruptedException e) {
System.err.println("Thread interrupted!");
}
}
}
public static void main(String [] orgs){
CThreadUsingThread thread = new CThreadUsingThread();
thread.start();
}
}
答案 0 :(得分:6)
你的代码基本上是误导性的。 看起来就像你指的是一个特定的线程,当实际上它只是调用总是指的静态Thread.sleep
方法当前正在执行的线程。
在这种特殊情况下,它并非非常误导,但它仍然不是很好。考虑一下这个更糟糕的情况:
CThreadUsingThread thread = new CThreadUsingThread();
thread.start();
thread.sleep(1000);
看起来哪个线程会发送到睡眠状态? 实际要发送到哪个线程?
顺便说一句,我也是:
C
前缀; CThreadUsingThread
不是传统的Java名称Runnable
并将其传递给Thread
构造函数,而不是直接对Thread
进行子类化。这是一个更清晰的代码分离,它明确地涉及线程和代码,它只是给线程一些代码来运行。答案 1 :(得分:2)
Thread.sleep
是一种static
方法。 Java允许您使用引用变量访问静态方法,但从语法来看,它不是一个静态方法的调用。
从类名而不是从引用变量调用静态方法总是更清楚。
答案 2 :(得分:1)
因为Thread.Sleep是静态的,所以您使用Thread实例调用静态方法。没有必要这样做。
此外,扩展Thread并不是一个好主意。在自定义类中包装线程很好。