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++;
}
}
source
share