当前位置:首页 > Java 语言特性 > 正文

Java优学网synchronized短文:掌握Java同步锁机制,轻松解决多线程并发问题

public synchronized void method() {

// 方法体

}

public class Counter {

private int count = 0;

public synchronized void increment() {
    count++;
}

public synchronized int getCount() {
    return count;
}

}

Java优学网synchronized短文:掌握Java同步锁机制,轻松解决多线程并发问题

public class LockExample {

// 实例方法 - 对象锁
public synchronized void instanceMethod() {
    // 使用当前实例作为锁
}

// 静态方法 - 类锁  
public static synchronized void staticMethod() {
    // 使用Class对象作为锁
}

public void codeBlock() {
    // 对象锁
    synchronized(this) {
        // 使用当前实例作为锁
    }
    
    // 类锁
    synchronized(LockExample.class) {
        // 使用Class对象作为锁
    }
}

}

Java优学网synchronized短文:掌握Java同步锁机制,轻松解决多线程并发问题

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

}

你可能想看:

相关文章:

文章已关闭评论!