java - Why is this thread allowing another one to access its synchronized method? -
i have following codes. expected 1 thread execute synchronized method , allow 1 access same method. however, not case.
public class threads { /** * @param args */ public static void main(string[] args) { //thread th = new threads(); thread th = new thread (new thread1 ()); th.start(); thread th1 = new thread (new thread1 ()); th1.start(); } } class thread1 implements runnable{ string name = "vimal"; public void run() { system.out.println("runnable "+this.name); setname("manish"); } public synchronized void setname(string name){ try { system.out.println("thread "+thread.currentthread().getname()); wait(1000); this.name = name; system.out.println("name "+this.name); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
i have 1 output
runnable vimal thread thread-0 runnable vimal thread thread-1 name manish name manish
what use of synchronized here , how make method run before accesses it?
synchronized
has no effect here because not synchronizing on same object in both cases. when applied instance method, synchronized
keyword causes method synchronized on this
. in each case synchronizing on instance of thread1
, , there 2 of those.
the more interesting test when run same instance of thread1
in 2 threads simultaneously. in case, calling wait(1000)
bad thing because (as documented) releases lock on this
. want use thread.sleep(1000)
instead in code.
if need have 2 instances of thread1
, need synchronize on shared object, possibly this:
private static final object lockobject = new object(); public void setname(string newname) { synchronized(lockobject) { dosetname(newname); } }
Comments
Post a Comment