Thứ Năm, 16 tháng 6, 2016

the differences between using a static lock object (code A) and a non-static lock object (code B) for a synchronized block

The difference is simple: if the locked-on object is in a static field, then all instances of MyClass*will share that lock (i.e. no two objects will be able to lock on that object at the same time). If the field is non-static, then each instance will have its own lock, so only calls of the method on the same object will lock each other. When you use a static lock object: thread 1 calls o1.foo() thread 2 calls o1.foo(), will have to wait for thread 1 to finish thread 3 calls o2.foo(), will also have to wait for thread 1 (and probably 2) to finish When you use a non-static lock object: thread 1 calls o1.foo() thread 2 calls o1.foo(), will have to wait for thread 1 to finish thread 3 calls o2.foo(), it...
Read More »