2

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
C graphics
  • 7,308
  • 19
  • 83
  • 134

3 Answers3

6

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.
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Thread.sleep is a static method. Java allows you to access a static method with a reference variable, but from the syntax it's not clear that it's a call to a static method.

It's always clearer to call a static method from the class name instead of from a reference variable.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

Because Thread.Sleep is static, you are calling a static method with your Thread instance. It is not necessary to do so.

Also, it's not a good idea to extend Thread. Wrapping thread inside of a custom class is fine.

T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • `Wrapping thread inside of a custom class is fine` what you mean with this? Creating a Runnable instance and setting to the thread? – nachokk Jan 13 '14 at 20:00