您的位置:首页 > 其它

多线程环境下的单例实现

2015-09-22 00:27 357 查看
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();

}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: