Synchronizes object lock

I have a confusion about locking objects. In the class below, which has 4 methods, the addB () method is synchronized.

There are 4 threads in my scienario. When thread-2 accesses the addB () method (it creates a lock on the test object), will there be another access to the addC () or addD () stream at the same time?

Does an object block only one thread at a time?

class Test{
       private Integer a;
       private Integer b;
       private Integer c;
       private Integer d;


   public void addA(){
      synchronized(a) {
         a++;
      }
   }
   public synchronized void addB(){
         b++;
      }

   public void addC(){
         c++;
      }

   public void addD(){
         d++;
      }    
   }

EDIT: I have 3 threads (t1, t2 and t3), and each of them will access addB (), addC () and addD (). If thread t1 accesses the addB () method, can thread t2 use the addC () method at the same time? If not for the state t2?

class Test{
       private Integer a;
       private Integer b;
       private Integer c;
       private Integer d;


   public void addA(){
      synchronized(a) {
         a++;
      }
   }
   public synchronized void addB(){
         b++;
      }

   public synchronized void addC(){
         c++;
      }

   public synchronized void addD(){
         d++;
      }    
   }
+3
source share
5 answers

, .

- , a, , this ( , synchronized, ).

, addB() , . this, a, addC() addD() .

: , AtomicInteger, Integer s. , .

+4

, Lock # 1, Lock # 2. , , Threads .

# 1

   public void addA(){
      synchronized(a) {
         a++;
      }
   }

lock # 2 (this)

   public synchronized void addB(){
         b++;
      }

addC() addD() , .

+1

- , , "", . , .

C D .

, a++ Integer.

+1

. , AddB .   , .

0

:

class MyClass extends Thread{
   Test instanceObj=null;    
   public MyClass(Test obj){
      instanceObj=obj;
   }

   public void run(){
      obj.addB();
   }
}

addB()

public void addB(){
  synchronized(this){
    //func
 }
}
  • . .
  • More over the addA lock is the obj.a object, which has its own independent lock. Two different threads can attach addA and addB at the same time.
0
source

Source: https://habr.com/ru/post/1751443/


All Articles