线程:单例懒汉式线程安全
2020-12-13 01:50
标签:read art single 判断 col imp 次数 get zed 线程:单例懒汉式线程安全 标签:read art single 判断 col imp 次数 get zed 原文地址:https://www.cnblogs.com/yumengfei/p/11012690.htmlpublic class Demo1 {
public static void main(String[] args) {
Test test = new Test();
Thread t0 = new Thread(test);
Thread t1 = new Thread(test);
t0.start();
t1.start();
}
}
class Test implements Runnable{
public void run() {
SingleInstance2 singleInstance2 = SingleInstance2.getInstance();
}
}
//饿汉式,由于公共方法中只有一行公共的代码,所以不会产生线程安全问题
class SingleInstance1{
private static final SingleInstance1 s = new SingleInstance1();
private SingleInstance1() {
}
public static SingleInstance1 getInstance() {
return s;
}
}
//懒汉式,
class SingleInstance2{
private static SingleInstance2 s = null;
private SingleInstance2() {
}
public static SingleInstance2 getInstance() {
if (s == null) {//尽量减少线程安全代码的判断次数,提高效率
synchronized (SingleInstance2.class) {//使用同步代码块儿实现了线程安全
if (s == null) {
s = new SingleInstance2();
}
}
}
return s;
}
}
下一篇:Unity脚本启动顺序调整方法