作用在成员方法上的锁:对象锁
class Test{
public synchronized void test() {
}
}
//等价于
class Test{
public void test() {
synchronized(this) {
}
}
}
作用在静态方法上的锁:也叫类锁
class Test{
public synchronized static void test() {
}
}
//等价于
class Test{
public static void test() {
synchronized(Test.class) {
}
}
}
例:
@Slf4j
public class Test1 {
public static void main(String[] args) throws InterruptedException {
Room room = new Room();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 5000; i++) {
room.increment();
}
}, "t1");
Thread t2 = new Thread(() -> {
for (int i = 0; i < 5000; i++) {
room.decrement();
}
}, "t2");
t1.start();
t2.start();
t1.join();
t2.join();
log.debug("count:{}", room.getCount());
}
}
class Room {
private int count = 0;
public void increment() {
synchronized (this) {
count++;
}
}
public synchronized void decrement() {
count--;
}
public synchronized int getCount() {
return count;
}
}