java - Class has 2 synchronized methods..when a thread is inside second method can another thread enter into first method? -



java - Class has 2 synchronized methods..when a thread is inside second method can another thread enter into first method? -

i know question "do 2 synchronized methods execute simultaneously" have been asked before , reply given " no. 1 thread can hold lock of object. , it's thread can come in synchronized methods on object." however, if true please help me understand output of below code :

public class synchronizationmistake { public int count; public synchronized int getcount() { homecoming count; } public synchronized string incrementcount() { count++; return""; } public static void main (string args[]) { synchronizationmistake syn = new synchronizationmistake(); thread first = new thread(syn.new readincrementcount(syn),"first"); thread sec = new thread(syn.new readincrementcount(syn), "second"); thread 3rd = new thread(syn.new readincrementcount(syn), "third"); first.start(); second.start(); third.start(); } private class readincrementcount implements runnable { synchronizationmistake syn; readincrementcount(synchronizationmistake syn) { this.syn = syn; } @override public void run() { system.out.println("i "+thread.currentthread().getname()+".count "+ syn.getcount()); system.out.println("i "+thread.currentthread().getname()+".incrementing count now"+syn.incrementcount()); system.out.println("i "+thread.currentthread().getname()+". after increment count "+ syn.getcount()); } }

}

output : first.count 0 first.incrementing count first. after increment count 1 third.count 0 second.count 0 third.incrementing count second.incrementing count third. after increment count 3 second. after increment count 3

output varies every time run program. uncertainty when second/third thread got cpu why didn't read 'count' 1 ( updated first thread)? in other words while first thread had lock on 'syn' , updating count 1 how did second/third thread managed come in 'getcount'method.

the statement system.out.println("i "+thread.currentthread().getname()+".count "+ syn.getcount()); not executed in atomic way. part syn.getcount() can executed way before println. seems happen in example. threads syn.getcount() first, count still 0 @ time, , execute rest.

java multithreading

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -