Synchronizing on other objects in java
This question already has an answer here:
Either way is fine. There are design reasons to use your object as the lock, and there are design reasons to keep the lock private as you have done.
The only critisizm I would make is that Object
typically gets used as a lock in Java, you don't have to invent a dummy class.
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private final Object lock1 = new Object();
private final Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
链接地址: http://www.djcxy.com/p/76262.html
下一篇: 在Java中同步其他对象