import java.util.concurrent.locks.ReentrantLock;
public class Singleton {
private static Singleton instance;
private static ReentrantLock lock = new ReentrantLock();
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
try{
lock.lock();
if (instance != null){
return instance;
}
instance = new Singleton();
} finally{
lock.unlock();
}
return instance;
} else {
return instance;
}
}
public static void main(String[] args) {
Thread[] threads = new Thread[100];
for (Thread t : threads) {
t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(getInstance());
}
});
t.start();
}
}
}
多线程环境下的单例实现
最新推荐文章于 2025-07-01 22:44:16 发布