您的位置:首页 > 编程语言 > Java开发

【Java基础】线程笔记——线程安全的单例模式的写法

2017-03-27 11:07 344 查看

线程安全,高并发性能不高

public class SingletonOne {

private static SingletonOne instance;

private static ReentrantLock lock = new ReentrantLock();

private SingletonOne(){

}

public static SingletonOne getInstance(){
if(instance == null){
lock.lock();
if(instance == null){
instance = new SingletonOne();
}
lock.unlock();
}
return instance;
}

}


线程安全、性能高

public class SingletonTwo {

private static SingletonTwo instance;

private static byte[] lock = new byte[0];

private SingletonTwo(){

}

public static SingletonTwo getInstance(){
if(instance == null){
synchronized (lock) {
if(instance == null){
instance = new SingletonTwo();
}
}
}
return instance;
}

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