java - Why does the synchronized lock another method? -
i'm new multiple-thread in java.i write class test functions of synchronized.i have method using synchronized:
public class shareutil { private static queue<integer> queue = new linkedlist<integer>(); public static synchronized void do1(){ system.out.println("do1"); sleep(); } public static synchronized void do2(){ system.out.println("do2"); sleep(); } private static void sleep(){ try { thread.sleep(1000*50000); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
you can see there 2 method using synchronized,and run 2 thread use these 2 methods respectively.
class run1 implements runnable{ @override public void run() { // todo auto-generated method stub shareutil.do1(); } } class run2 implements runnable{ @override public void run() { // todo auto-generated method stub shareutil.do2(); } } public class domain { public static void main(string[] args) { executorservice pools = executors.newcachedthreadpool(); for(int i=0;i<10;i++){ pools.execute(new run1()); pools.execute(new run2()); } pools.shutdown(); } }
but,it print "do1" not print "do2".i want know why?the key of "synchronized" using method make method 1 thread use @ same time,but why lock others method?
the important key synchronized
locks object, not method.
according https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
every object has intrinsic lock associated it. convention, thread needs exclusive , consistent access object's fields has acquire object's intrinsic lock before accessing them, , release intrinsic lock when it's done them. thread said own intrinsic lock between time has acquired lock , released lock. as long thread owns intrinsic lock, no other thread can acquire same lock. other thread block when attempts acquire lock.
so, shareutil 's class intrinsic lock(your method static
, intrinsic lock class object associated class) is locked when thread t1 doing do1(), no other thread can acquire lock unless t1 release it.
and method sleep()
call not release lock , while if call wait()
, check difference between wait() , sleep(). is reason why when thread t2 try access do2(), must wait t1's do1() complete(intrinsic lock released).
Comments
Post a Comment