同步块/代码 Java 上的线程访问

2022-01-22 00:00:00 multithreading synchronization java

我正在阅读 Synchronized 工作.示例如下:

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;
}

假设两个线程 AB 正在访问 getInstance(); 方法,如果线程 Asynchronized 块中,则线程 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.classsynchronized参数中,什么时候可能是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

顺便说一句.

public synchronized void method1(){...}

相当于:

public void method1(){
    synchronized(this){
        ...
    }
}

相关文章