java - Why the below program, without a sleep go to deadlock state but with sleep it executes all the three threads and terminates normally? -
public class threadtest { public static void main(string[] args) throws interruptedexception { exampletest obj = new exampletest(); thread t1 = new thread(new runn(obj)); thread t2 = new thread(new runn(obj)); thread t3 = new thread(new runn(obj)); t1.start(); t2.start(); t3.start(); //thread.sleep(1); obj.exit(); }
}
class exampletest { public synchronized void enter() { try { system.out.println("printed " +thread.currentthread().getname() +" inside wait"); this.wait(); system.out.println("printed " +thread.currentthread().getname() +" exit wait"); } catch (interruptedexception e) { e.printstacktrace(); } system.out.println("printed " +thread.currentthread().getname() +" @ time: "+system.currenttimemillis()); } public synchronized void exit() { this.notifyall(); }
}
class runn implements runnable { exampletest obj; public runn(exampletest obj) { this.obj = obj; } @override public void run() { obj.enter(); }
}
what role of notifyall(). notifyall() allows waiting thread acquire lock sequentially in random order or 1 thread can acquire lock?
without sleep statement statement obj.exit();
executed before of threads reaching wait status. ie. notifyall
call on before @ least 1 of thread in wait status. @ least 1 of threads stuck in wait status waiting other thread notify , wake up. never happen obj.exit() finished.
with sleep statement in place , of threads chance reach wait status , notifyall call after sleep wake them all, order of waking not deterministic , handled thread scheduler.
Comments
Post a Comment