Threads access on Synchronized Block/Code Java

帅比萌擦擦* 提交于 2019-12-02 08:59:44

问题


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

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 What is, why is Singleton.class in synchronized parameter and when it could be null

and the below Statement is true?

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:


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 is the object, that represent that class. You are synchronizing on it, since your _instance-object is null.

public synchronized void method1(){...}

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();

last question: right, Thread B will not enter method 2, since the synchronized method locks on the Object

Btw.

public synchronized void method1(){...}

is equivalent to:

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



回答2:


See here for documentation on the synchronized keyword.

Using synchronized on a method will only allow one thread at a time to access the method. All other threads will block and be queued for execution. When you use this keyword, the instance object is used as a lock to synchronize the execution. If you are calling methods on the same object only one thread can hold the lock at a time so your statement is true.

Using the synchronized keyword on a method can be performance-degrading, and it's recommended to use the Java concurrency API instead, see here.



来源:https://stackoverflow.com/questions/32936374/threads-access-on-synchronized-block-code-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!