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

前端 未结 2 933
我寻月下人不归
我寻月下人不归 2020-12-09 14:05

I wrote a simple code to mock concurrency using Lock and synchronized.

Source code is as follows:

Task class inclu

2条回答
  •  忘掉有多难
    2020-12-09 15:02

    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

提交回复
热议问题