java - How to put a particular thread to sleep()? -
i reading sleep() method of threads. tried develop small example. have 2 confusions regarding example.
/** * created intellij idea. * user: ben * date: 8/7/13 * time: 2:48 pm * change template use file | settings | file templates. */ class sleeprunnable implements runnable{ public void run() { for(int =0 ; < 100 ; i++){ system.out.println("running: " + thread.currentthread().getname()); } try { thread.sleep(500); } catch(interruptedexception e) { system.out.println(thread.currentthread().getname() +" 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(); } }
- as discussed in last posts, interrupted exception occur if thread wakes after specified amount of time , return run method. in example of mine, code never enters catch() block. why so?
- now, of threads in above example sleep second , take turns gracefully, if wanted make thread "ben" sleep. don't think possible in example.
can elaborate on concept little further.
as discussed in last posts, interrupted exception occur if thread wakes after specified amount of time , return run method. in example of mine, code never enters catch() block. why so?
you not calling interrupt()
anywhere in code.
t1.interrupt(); //this throw exception when t1 sleeping
now, of threads in above example sleep second , take turns gracefully, if wanted make thread "ben" sleep. don't think possible in example.
threads not taking turns in example precise, working individually without knowing each other.
hint: check name of current thread , sleep if name ben
.
thread.currentthread().getname() //for getting name of current thread
edit:
reproducing interruption: increase sleep interval 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 main thread sleep sec //time interrupt t1 !!!! t1.interrupt(); //throws interrupted exception in run method of thread t1
Comments
Post a Comment