李蜜简介,收获快乐,黑龙江旅游职业学院
package designpattern.singleton; public class hungrysingleton { private static hungrysingleton instance = new hungrysingleton();// 静态初始化 private hungrysingleton() {// 私有化构造方法 } public static hungrysingleton getinstance() {// 获取实例,static的 return instance; } }
package designpattern.singleton; public class lazysingleton { private static lazysingleton instance; private lazysingleton() {// 私有化构造方法 } public static lazysingleton getinstance() {// 获取实例,static的 if (instance == null) { instance = new lazysingleton();// 方法中创造实例 } return instance; } }
package designpattern.singleton; public class lazysingleton2 { private static lazysingleton2 instance; private lazysingleton2() { } public static synchronized lazysingleton2 getinstance() {// synchronized 修饰 if (instance == null) { instance = new lazysingleton2(); } return instance; } }
package designpattern.singleton; import java.util.concurrent.locks.lock; import java.util.concurrent.locks.reentrantlock; public class lazysingleton3 { private static lazysingleton3 instance; private static lock lock = new reentrantlock(); private lazysingleton3() { } public static synchronized lazysingleton3 getinstance() { try { if (instance == null) { lock.lock(); if (instance == null) {// 有必要再次判断,不然还是存在线程安全问题 instance = new lazysingleton3(); } lock.unlock(); } } finally {// 保证锁被释放 lock.unlock(); } return instance; } }
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
java多线程定时器和java判断一个时间是否在时间区间内和用正则表达式获取String字符串之间的数据
网友评论