有什么区别
synchronized(classname.class)
vs synchronized(this)
vs synchronized(AnyObjectName)
?
当同步块只需要任何对象时,为什么所有三个都会产生不同的答案?
答案 0 :(得分:1)
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
因此,在synchronized块中,您可以显式指定锁定。在同步方法中,'this'是默认的锁。对于静态同步方法,'CalssName.class'是锁。
答案 1 :(得分:1)
synchronized(this)在当前对象上同步,因此只有一个线程可以访问每个实例,但不同的线程可以访问不同的实例。例如。每个线程可以有一个实例。
synchronized(SomeClass.class)在当前对象(或其他类,如果有人)的类上同步,因此只有一个线程可以访问该类的任何实例。
synchronized(classname.class)
的用法 public class MyClass {
public static synchronized void log1(String msg1, String msg2){
log.writeln(msg1);
log.writeln(msg2);
}
public static void log2(String msg1, String msg2){
synchronized(MyClass.class){
log.writeln(msg1);
log.writeln(msg2);
}
}
}
只有一个线程可以同时在这两个方法中的任何一个内执行。
如果第二个同步块在与MyClass.class不同的对象上同步,则可以在每个方法内同时执行一个线程。