What's the difference between Synchronized and Lock in my example?

白昼怎懂夜的黑 提交于 2019-11-28 08:51:05

First of all, your example using synchronized is ill conceived: it is a very bad idea to synchronize on object "A". Use the following idiom instead:

private final Object lock = new Object();

public void run() {
    synchronized (lock) {
        doSomething();
    }
}

This is better because by hiding your lock from external objects, you are encapsulating your synchronization protocol and thereby implementing a safer synchronization policy.

Now, the difference between synchronized and java.util.concurrent.locks.Lock, is that the former is a synchronization primitive whereas the latter a higher level locking construct which provides more elaborate operations than synchornized.

Fore more information you may look at http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html and http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html in particular.

Phoen-X
synchronized ("A")

it's not a proper usage of synchronized block. you create a different String object (in some cases) when entering this sync block, so each your thread have a different lock object and do not synchronize. Proper usage may be like

synchronized(this)

or

public class TaskWithSync extends Task implements Runnable {
    private Object lock = new Object();

    @Override
    public void run() {

        synchronized (lock) {
            doSomething();
        }
    }
}

In addition, you should use a single Runnable implemenation in different threads, or make your lock a static field

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