java - Trying to understand synchronized methods -
for code below, expected output is:
waiting b complete... total is: 4950 how come can't print total is.. first waiting b.. after? i'd think b.start() executed first in cases, holds onto threadb's lock synchronized(this) in threadb.run() blocking main entering in synchronized(b).
is wrong stated?
public class threada { public static void main(string[] args) { threadb b = new threadb(); b.start(); synchronized(b) { try{ system.out.println("waiting b complete..."); b.wait(); } catch(interruptedexception e) { e.printstacktrace(); } system.out.println("total is: " + b.total); } } } class threadb extends thread { int total; @override public void run() { synchronized(this) { for(int i=0; i<100 ; i++) { total += i; } notify(); } } }
the 2 output statements always have same order, because executed on 1 thread. waiting thread finish between them not change execution order.
if put "total ..." output end of b's run() there might chance seeing indeterministic orders of outputs.
edit - please note @holger 's comment answer:
[...] in unlikely, still possible case threadb’s synchronized block executed first, notify() call have no effect no-one waiting yet , then, threada’s wait() call may hang forever there no subsequent notification.
Comments
Post a Comment