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