Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 215
benz Avatar asked Dec 16 '22 07:12

benz


1 Answers

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) {}
}
like image 133
Tala Avatar answered Dec 31 '22 08:12

Tala