Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement