在上面的示例中,ReentrantLockExample 并不是单例。它只是一个普通的类,用于演示如何使用 ReentrantLock。

如果你想要将 ReentrantLockExample 设计为单例,可以使用常见的单例模式实现方式之一。以下是一个简单的单例模式示例:

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {
    private static volatile ReentrantLockExample instance;
    private final ReentrantLock lock = new ReentrantLock();

    private ReentrantLockExample() {
        // 私有构造函数
    }

    public static ReentrantLockExample getInstance() {
        if (instance == null) {
            synchronized (ReentrantLockExample.class) {
                if (instance == null) {
                    instance = new ReentrantLockExample();
                }
            }
        }
        return instance;
    }

    public void performTask() {
        lock.lock();
        try {
            // 执行需要同步的代码块
            // ...
        } finally {
            lock.unlock();
        }
    }
}

在上面的示例中,我们使用双重检查锁(double-checked locking)来保证单例的线程安全性。getInstance() 方法使用了双重检查锁机制,确保只有在实例未被创建时才进行实例化。

请注意,这是一种常见的单例模式实现方式,但在多线程环境下需要注意正确处理 volatile 关键字和锁的使用,以确保线程安全性。

ReentrantLockExample 是单例吗? - 深入理解 Java 单例模式

原文地址: https://www.cveoy.top/t/topic/jru 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录