Which Thread.sleep commands pauses which threads?

I have four declarations of Thread.sleep(...) below. Each of the declarations is marked with that Line #1 to #6. My question is which declarations put which threads to pause?

class Runa extends Thread{
    public void run(){
        try{
            // Line #1
            Thread.sleep(500);
            //Line #2
            this.sleep(500);
        }catch(Exception e) {}
    }
}

class Runb implements Runnable {
    Thread t;

    Runb() {
        t = new Thread(this);
        t.start();

        try{
            //Line #3
            Thread.sleep(500);

        }catch(Exception e){ }
    }

    @Override
    public void run() {
     
        try {
            do {

                // Line #4
                Thread.sleep(2000);
                // Line #5
                // t.sleep(500);
                count++;
            } while (count < 10);
        } catch (InterruptedException e) {

        }

    }
}

public class thread2Runnable2 {
    public static void main(String args[]) {          
        Runa rua = new Runa();
        rua.start();
        //Line #6
        rua.sleep(500); 
       
        Runb runb = new Runb();    
    }
}

These are my assumptions:

Line #1 pause Runa thread
Line #2 pause Runa thread
Line #3 pause the main thread
Line #4 pause t thread
Line #5 pause t thread
Line #6 pause the main thread

Are my assumptions correct?

Upvotes: 0

Views: 117

Answers (2)

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

Thread.sleep() is a static method, so it doesn't matter which object you call it on: it will always act on the currently executing thread.

The fact that you can call this method on an instance (e.g. runa) syntax-wise at all is a quirk of Java and can be very confusing. Many IDEs and other code-quality tools will highlight such calls as warnings as the object reference is completely irrelevant to the call and thus can be misleading to someone reading the code.

If you use the normal static call syntax, Thread.sleep(NNNN), you see that no object reference is passed, which, even without reading the documentation, easily leads to the conclusion that the only reasonable behavior is to act on current thread.

Upvotes: 5

Slaw
Slaw

Reputation: 45866

The Thread#sleep(long) method is a static method which:

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 currently executing thread is the thread which invoked the method. So whichever thread invokes sleep is the one which sleeps. As far as I can tell, your assumptions appear correct.

Upvotes: 6

Related Questions