java - Does interrupt exception to a sleeping thread release lock on the object -
when thread on sleep state still holds lock object, , when interrupted, release lock , go ready state or continue execution without changing state?
when interrupted, release lock , go ready state or continue execution without changing state?
being interrupted thread status change (a flag has been set) not state change, , has not effect on whether release lock or not.
a thread holding object's monitor release if calls wait
(with or without timeout) on corresponding object instance or when exit synchronized block, being interrupted or not doesn't change rule.
here simple code shows idea:
// used make sure thread t holds lock before t2 countdownlatch latch = new countdownlatch(1); thread t = new thread( () -> { synchronized (someobject) { // release t2 latch.countdown(); (int = 1; <= 2; i++) { try { system.out.println("sleeping " + i); // sleep 2 sec , keep holding lock thread.sleep(2_000l); system.out.println("sleep on " + i); } catch (interruptedexception e) { system.out.println("interrupted " + i); } } } } ); thread t2 = new thread( () -> { try { // wait release t latch.await(); } catch (interruptedexception e) { throw new illegalstateexception(e); } system.out.println("trying in"); synchronized (someobject) { system.out.println("in"); } } ); // start threads t.start(); t2.start(); // waiting 1 sec (< 2 sec) before interrupting t thread.sleep(1_000l); // interrupt t t.interrupt();
output:
trying in sleeping 1 interrupted 1 sleeping 2 sleep on 2 in
as can see in output thread t2
gets synchronized block (acquires lock) when thread t
exits synchronized block. fact thread t
has been interrupted did not make release lock.
Comments
Post a Comment