Why for creation of delay the static refrence to Thread.sleep is preferred not this.sleep?

In the code below the compiler suggested me to use Thread.sleep (the static reference ) not this.sleep, why is that?

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();
    }
}

Also attached the image to make it more visible

Jon Skeet
people
quotationmark

Your code is misleading, basically. It looks like you're referring to a specific thread, when actually it's just calling the static Thread.sleep method which always refers to the currently executing thread.

In this particular case it's not hugely misleading, but it's still not nice. Consider this rather worse case though:

CThreadUsingThread thread  = new CThreadUsingThread();
thread.start();
thread.sleep(1000);

Which thread does it look like that will send to sleep? And which thread is it actually going to send to sleep?

As an aside, I'd also:

  • Avoid the C prefix for classes; CThreadUsingThread isn't a conventional Java name
  • Prefer creating a Runnable and passing that to the Thread constructor, rather than subclassing Thread directly. It's a cleaner separation of code which is explicitly about threading and code which is just giving the thread some code to run.

people

See more on this question at Stackoverflow