指在实例方法或代码块上使用 synchronized 关键字,这样锁定的是当前实例对象 (this)。
public class Example {
public synchronized void instanceMethod() {
// 代码块
}
public void anotherInstanceMethod() {
synchronized (this) {
// 代码块
}
}
}
指在静态方法或代码块上使用 synchronized 关键字,这样锁定的是类对象 (Class 对象)。
public class Example {
public static synchronized void classMethod() {
// 代码块
}
public void anotherClassMethod() {
synchronized (Example.class) {
// 代码块
}
}
}
public class Example {
// 锁实例方法
public synchronized void instanceMethod() {
System.out.println(Thread.currentThread().getName() + " is in instanceMethod");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is leaving instanceMethod");
}
// 锁类方法
public static synchronized void classMethod() {
System.out.println(Thread.currentThread().getName() + " is in classMethod");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is leaving classMethod");
}
public static void main(String[] args) {
Example example1 = new Example();
Example example2 = new Example();
// 锁实例(不同示例之间代码不互斥)
new Thread(() -> example1.instanceMethod(), "Thread-1").start();
new Thread(() -> example2.instanceMethod(), "Thread-2").start();
// 锁类(代码互斥,只能允许一个线程先执行)
new Thread(() -> Example.classMethod(), "Thread-3").start();
new Thread(() -> Example.classMethod(), "Thread-4").start();
}
}