java - why Interrupted exception thrown here...reason? -


public class twothreads {     private static object resource = new object();      private static void delay(long n) {         try          {              thread.sleep(n);         }         catch (exception e)         {               e.printstacktrace();         }     }      public static void main(string[] args) {         system.out.print("startmain ");         new thread1().start();         delay(1000);                       //dealay 1         thread t2 = new thread2();         t2.start();            delay(1000);                      // delay 2             t2.interrupt();                   //here throwing exception         delay(1000);                      //delay 3         system.out.print("endmain ");     }      static class thread1 extends thread {         public void run() {             synchronized (resource) {                 system.out.print("startl ");                 delay(6000);                 system.out.print("end1 ");             }         }     }      static class thread2 extends thread {         public void run() {             synchronized (resource) {                 system.out.print("start2 ");                 delay(2000);                 system.out.print("end2 ");             }         }     } } 

i got confused here why t2.interrupt() not throwing exception when t2 waiting acquire lock on resource object , interrupt() method might throw security exception why compiler still allowing execute without putting try catch block.

a synchronized block doesn't throw interruptedexception , interrupting thread blocking while attempting acquire monitor way doesn't anything.

if want functionality need use lock has lockinterruptibly(), though not used.

acquires lock unless current thread interrupted. acquires lock if not held thread , returns immediately, setting lock hold count one.

if current thread holds lock hold count incremented 1 , method returns immediately.

if lock held thread current thread becomes disabled thread scheduling purposes , lies dormant until 1 of 2 things happens:

the lock acquired current thread; or other thread interrupts current thread. if lock acquired current thread lock hold count set one.

if current thread: has interrupted status set on entry method; or interrupted while acquiring lock, interruptedexception thrown , current thread's interrupted status cleared.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -