Threads access on Synchronized Block/Code Java

守給你的承諾、 提交于 2019-12-02 04:27:44

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.

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