Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways of calling sleep method in threads

I am a beginner to threading. I dont know exactly what is the difference between the three different types of way the thread object has called the sleep method. Also can you please clarify in which type of cases there is a limitation on using the way the sleep method has been called

The code is given below

    // implementing thread by extending THREAD class//

class Logic1 extends Thread
{
    public void run()
    {
        for(int i=0;i<10;i++)
        {
            Thread s = Thread.currentThread();
            System.out.println("Child :"+i);
            try{
                s.sleep(1000);              // these are the three types of way i called sleep method
                Thread.sleep(1000);         //      
                this.sleep(1000);           //
            } catch(Exception e){

            }
        }
    }
}

class ThreadDemo1 
{
    public static void main(String[] args)
    {
        Logic1 l1=new Logic1();
        l1.start();
    }
}
like image 503
roshan dhb Avatar asked Aug 19 '13 15:08

roshan dhb


3 Answers

sleep() is a static method that always references the current executing thread.

From the javadoc:

/**
 * Causes the currently executing thread to sleep (temporarily cease
 * execution) for the specified number of milliseconds, subject to
 * the precision and accuracy of system timers and schedulers. The thread
 * does not lose ownership of any monitors.
 *
 * @param  millis
 *         the length of time to sleep in milliseconds
 *
 * @throws  IllegalArgumentException
 *          if the value of {@code millis} is negative
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
public static native void sleep(long millis) throws InterruptedException;

These calls

s.sleep(1000); // even if s was a reference to another Thread
Thread.sleep(1000);      
this.sleep(1000);     

are all equivalent to

Thread.sleep(1000);  
like image 161
Sotirios Delimanolis Avatar answered Oct 19 '22 15:10

Sotirios Delimanolis


In general, if ClassName.method is a static method of ClassName, and x is an expression whose type is ClassName, then you can use x.method() and it will be the same as calling ClassName.method(). It doesn't matter what the value of x is; the value is discarded. It will work even if x is null.

String s = null;
String t = s.format ("%08x", someInteger);  // works fine 
                                            // (String.format is a static method)
like image 2
ajb Avatar answered Oct 19 '22 17:10

ajb


All three are same. These are different way to reference the currently executing thread.

like image 1
Ragavan Avatar answered Oct 19 '22 17:10

Ragavan