benz
benz

Reputation: 4629

How to put a particular thread to sleep()?

I was reading sleep() method of Threads. I tried to develop a small example. I have two confusions regarding this example.

/**
 * Created with IntelliJ IDEA.
 * User: Ben
 * Date: 8/7/13
 * Time: 2:48 PM
 * To change this template use File | Settings | File Templates.
 */

class SleepRunnable implements Runnable{

  public void run() {
    for(int i =0 ; i < 100 ; i++){
      System.out.println("Running: " + Thread.currentThread().getName());
    }
    try {
      Thread.sleep(500);
    }
    catch(InterruptedException e) {
      System.out.println(Thread.currentThread().getName() +" I have been interrupted");
    }
  }
}

public class ThreadSleepTest {
  public static void main(String[] args){
    Runnable runnable = new SleepRunnable();
    Thread t1 = new Thread(runnable);
    Thread t2 = new Thread(runnable);
    Thread t3 = new Thread(runnable);
    t1.setName("Ben");
    t2.setName("Rish");
    t3.setName("Mom");
    t1.start();
    t2.start();
    t3.start();
  }
}
  1. As i discussed in my last posts, interrupted exception will occur if a thread wakes up after a specified amount of time and it will simply return from the run method. In this example of mine, the code never enters the catch() block. Why is it so?
  2. Now, all of the threads in the above example will sleep for a second and will take turns gracefully, what if i specifically wanted to make the thread "Ben" sleep. I don't think so it is possible in this example.

Can someone elaborate on this concept a little further.

Upvotes: 4

Views: 7051

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136152

1) Not true, InterruptedException will NOT occur if a thread wakes up after the specified timeout, the thread will simply resume running. Your code does not enter catch block because it was never interrupted, try this

...
t3.start();
t3.interrupt();
...

if you want to see InterruptedException from t3.

2) I think you can do something like this

...
if (Thread.currentThread().getName().equals("Ben")) {
    try {
      Thread.sleep(500);
    }
    ...

}

Upvotes: 2

Narendra Pathai
Narendra Pathai

Reputation: 42005

As i discussed in my last posts, interrupted exception will occur if a thread wakes up after a specified amount of time and it will simply return from the run method. In this example of mine, the code never enters the catch() block. Why is it so?

You are not calling interrupt() anywhere in your code.

t1.interrupt(); //this will throw the exception when t1 is sleeping

Now, all of the threads in the above example will sleep for a second and will take turns gracefully, what if i specifically wanted to make the thread "Ben" sleep. I don't think so it is possible in this example.

Threads are not taking turns in this example to be precise, they are working individually without knowing about each other.

HINT: check for the name of the current thread and sleep if the name is Ben.

Thread.currentThread().getName() //for getting the name of the current thread

EDIT:

Reproducing interruption: increase the sleep interval to 10000 milliseconds

Main method code:

Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
Thread t3 = new Thread(runnable);
t1.setName("Ben");
t2.setName("Rish");
t3.setName("Mom");
t1.start();
t2.start();
t3.start();

Thread.sleep(1000); //make the main thread to sleep for a sec

//time to interrupt t1 !!!!
t1.interrupt();   //throws Interrupted exception in the run method of Thread t1

Upvotes: 4

Levente Kurusa
Levente Kurusa

Reputation: 1866

InterruptedException will only occur if the Runtime must wake up the process. Putting a thread to sleep via sleep() will make it escape the processor's thread queue. If it for some reason needs its attention, then it will fire an InterruptedException InterruptedException may also occur, while it is running and the processor must take away the control from the thread before its timeslice is used up, mainly because there is a higher piority task starving for attention. At least, that is what I recall! :)

Upvotes: 0

Tala
Tala

Reputation: 8938

1.When timout is reached no InterruptedException is thrown. It is thrown when you interrupt thread that is sleeping at the moment.

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect: if (Thread.interrupted()) // Clears interrupted status! throw new InterruptedException();

2.Executing code can only make sleep it's current thread. So you can determnie your thread by name for example:

if ("Ben".equals(Thread.currentThread().getName())) { 
try {
  Thread.sleep(500);
} catch (InterruptedException e) {}
}

Upvotes: 6

Related Questions