java - Java 同步块(synchronized block)/代码上的线程访问

标签 java multithreading synchronization

我正在阅读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;
}

假设两个线程 AB 正在访问 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 then threadB cannot enter method2 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/

相关文章:

c# - MSBuild BuildInParallel,无法运行的自定义任务生成过程

c# - 同步多个 View 、编辑器和提交/取消

node.js - 如何在 node.js 的单个进程中同步对文件的访问?

Java 线程同时递增和递减 int

尝试运行 Grails 时出现 Java 异常

java - Java 游戏中的 key 管理器

java - 如何使用 JMockit 模拟/伪造一个新的枚举值

java - 在 Spring Webflow 单元测试中设置 messages.properties

java - 我需要从线程返回一些东西

c++ - 线程安全计数器c++11