本帖最后由 罗中扬 于 2014-6-11 10:23 编辑
- package com.lzy.dome;
- public class Test5 {
- /**
- * “懒汉式”单例设计模式
- *
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- }
- }
- // 懒汉式1 加同步代码块 但是每次判断锁 低效
- class Single {
- private static Single single = null;
- private Single() {
- }
- public static synchronized Single getInstance() {
- if (single == null) {
- single = new Single();
- }
- return single;
- }
- }
- //懒汉式2 减少了判读锁的次数 提高了效率
- class Single2 {
- private static Single2 single = null;
- private Single2() {
- }
- public static Single2 getInstance() {
- if (single == null) {
- synchronized (Single2.class) {
- if (single == null) {
- single = new Single2();
- }
- }
- }
- return single;
- }
- }
复制代码 |
|