问题描述
我正在阅读。以下是示例:
I was reading Synchronized working. Here is the example:
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();
方法,
如果线程
在 synchronized
块中,然后线程 B
将跳过该块并执行下一个块/语句或将等待/阻止,直到线程 A
保留 synchronized
块。
Let Suppose two Thread A
and B
are accessing getInstance();
method,If thread A
is in synchronized
block then thread B
will skip that block and execute next block/statement or will wait/blocked until Thread A
leave the synchronized
block.
2nd这是什么,为什么 Singleton.class
在 synchronized
参数中以及何时可以 null
2nd What is, why is Singleton.class
in synchronized
parameter and when it could be null
以及语句
是真的吗?
class A
{
public synchronized void method1(){...}
public synchronized void method2(){...}
}
如果线程A在 method1
中,那么 threadB
无法输入 method2
或任何其他同步方法。
If thread A is in method1
then threadB
cannot enter method2
or any other synchronized method .
推荐答案
1:线程B将等待,直到线程A将释放同步对象上的锁并执行代码,之后它将获取同步对象上的锁。
1: Thread B will wait, until Thread A will release the lock on the synchronized object and execute the code, after it will aquire the lock on the synchronized object.
2: Singleton.class
是表示该类的对象。您正在同步它,因为您的 _instance
-object为空。
2: Singleton.class
is the object, that represent that class. You are synchronizing on it, since your _instance
-object is null.
public synchronized void method1(){...}
正在对象上进行同步,就是你调用那个方法,也就是说,2个线程会互相等待,如果你这样称呼:
is synchronizing on the Object, on that you call that method, that means, 2 Threads will wait for each other, if you call it like this:
final A a = new A();
new Thread(new Runnable(){
public void run(){
a.method1();
}
}).start();
a.method1();
但如果你在不同的对象上调用它们,两个线程将并行执行:
but both threads will be executed parallel, if you call it on different Objects:
A a = new A();
final A b = new A();
new Thread(new Runnable(){
public void run(){
b.method1();
}
}).start();
a.method1();
最后一个问题:对,线程B不会进入方法2,因为同步方法锁定了对象
last question: right, Thread B will not enter method 2, since the synchronized method locks on the Object
Btw。
public synchronized void method1(){...}
相当于:
public void method1(){
synchronized(this){
...
}
}
这篇关于线程访问同步块/代码Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!