public synchronized void method() {
// 方法体
}
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class LockExample {
// 实例方法 - 对象锁
public synchronized void instanceMethod() {
// 使用当前实例作为锁
}
// 静态方法 - 类锁
public static synchronized void staticMethod() {
// 使用Class对象作为锁
}
public void codeBlock() {
// 对象锁
synchronized(this) {
// 使用当前实例作为锁
}
// 类锁
synchronized(LockExample.class) {
// 使用Class对象作为锁
}
}
}
public class Counter {
private int count = 0;
// 非同步方法 - 存在线程安全问题
public void increment() {
count++; // 这个操作不是原子的
}
// 同步方法 - 保证线程安全
public synchronized void safeIncrement() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class FineGrainedLock {
private final Object readLock = new Object();
private final Object writeLock = new Object();
private int readCount = 0;
private int writeCount = 0;
public void incrementRead() {
synchronized(readLock) {
readCount++;
}
}
public void incrementWrite() {
synchronized(writeLock) {
writeCount++;
}
}
}
你可能想看: