why Synchronized method allowing multiple thread to run concurrently?

后端 未结 1 1775
抹茶落季
抹茶落季 2020-12-03 16:11

I have following program in same file. I have synchronized the run() method.

class MyThread2 implements Runnable {
    Thread    t;

    MyThread2(String s)          


        
相关标签:
1条回答
  • 2020-12-03 16:26

    synchronized methods work at the instance level. Each instance of the class gets its own lock. The lock gets acquired every time any synchronized method of the instance is entered. This prevents multiple threads calling synchronized methods on the same instance (note that this also prevents different synchronized methods from getting called on the same instance).

    Now, since you have two instances of your class, each instance gets its own lock. There's nothing to prevent the two threads each operating on its own instance concurrently.

    If you do want to prevent this, you could have a synchronized(obj) block inside run(), where obj would be some object shared by both instances of your class:

    class MyThread2 implements Runnable {
       private static final Object lock = new Object();
       ...
       public void run() {
         synchronized(lock) {
           ...
         }
       }
    }
    
    0 讨论(0)
提交回复
热议问题