I wrote a simple code to mock concurrency using Lock and synchronized.
Source code is as follows:
Task class inclu
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.
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