java - How a sleeping thread can send interrupt to itself? -
i reading java threads. looking sleep()
method. books states that
when thread encounters
sleep
call, must go sleep specified amount of time, unless interrupted before wake-up time.
i reading interrupts, how can thread send interrupt itself? think thread can send interrupt? understanding correct? additionally, both of threads, 1 send interrupt should having same target runnable? if suppose thread interrupted, go runnable
state? sorry, if sounding stupid, it's pretty new me. thanks
a thread can't interrupt while sleeping, because is... sleeping.
a picture worth thousand words here simple example thread starts sleeping , main thread interrupts it:
public static void main(string[] args) throws exception { runnable sleeper = new runnable() { public void run() { try { system.out.println("sleeper going sleep"); thread.sleep(1000); system.out.println("sleeper awake"); } catch (interruptedexception e) { system.out.println("sleeper got interrupted"); } } }; thread t = new thread(sleeper); t.start(); //run sleeper in own thread thread.sleep(500); //sleeping in main little make sure t started t.interrupt(); }
which prints:
sleeper going sleep sleeper got interrupted
Comments
Post a Comment