简体   繁体   中英

Threads access on Synchronized Block/Code Java

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: 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){
        ...
    }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM