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();
}
}
Can someone elaborate on this concept a little further.
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) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With