我正在阅读Synchronized在职的。这是示例:
public class Singleton{
private static volatile Singleton _instance;
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
假设两个线程 A
和 B
正在访问 getInstance();
方法,
如果线程 A
位于 synchronized
block 中,则线程 B
将跳过该 block 并执行下一个 block /语句,或者将等待/阻塞,直到线程 A
离开synchronized
block 。
第二个是什么,为什么 Singleton.class
位于 synchronized
参数中以及何时可能为 null
下面的陈述
是真的吗?
Intrinsic locks are on the object:
class A { public synchronized void method1(){...} public synchronized void method2(){...} }
If thread A is in
method1
thenthreadB
cannot entermethod2
or any other synchronized method .
最佳答案
1:线程B将等待,直到线程A释放同步对象上的锁并执行代码,然后它才会获取同步对象上的锁。
2:Singleton.class
是代表该类的对象。您正在同步它,因为您的 _instance
对象为 null。
public synchronized void method1(){...}
在对象上同步,在你调用该方法时,这意味着,如果你这样调用它,2个线程将互相等待:
final A a = new A();
new Thread(new Runnable(){
public void run(){
a.method1();
}
}).start();
a.method1();
但是如果您在不同的对象上调用它,两个线程将并行执行:
A a = new A();
final A b = new A();
new Thread(new Runnable(){
public void run(){
b.method1();
}
}).start();
a.method1();
最后一个问题:对,线程B不会进入方法2,因为synchronized方法锁定了对象
顺便说一句。
public synchronized void method1(){...}
相当于:
public void method1(){
synchronized(this){
...
}
}
关于java - Java 同步块(synchronized block)/代码上的线程访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32936374/