设计模式之单例模式>>应用场景及实现
定义
单例模式(Singleton),也叫单子模式,是一种常用的软件设计模式。对于系统而言该实例有且仅有一个。
应用场景
线程池、数据库池、用于对系统做初始化的实例,提供给关联系统调用的接口(任务提交部分)
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。不适用成员变量多变的场景。
1、实现方式-饿汉模式

1 package com.learn.designpattern.singleton; 2 3 import java.util.concurrent.ArrayBlockingQueue; 4 import java.util.concurrent.ExecutorService; 5 import java.util.concurrent.ThreadPoolExecutor; 6 import java.util.concurrent.TimeUnit; 7 8 /** 9 * 10 * @author zhujj 11 */ 12 13 public class ThreadPoolUntil { 14 15 private final static ExecutorService executorService= new ThreadPoolExecutor(5,20,0,TimeUnit.SECONDS,new ArrayBlockingQueue<>(128)); 16 17 private ThreadPoolUntil() { 18 // TODO Auto-generated constructor stub 19 } 20 21 public static ExecutorService getIntance() { 22 return executorService; 23 } 24 public static void main(String[] arg0) { 25 ThreadPoolUntil.getIntance().execute(new Runnable() { 26 @Override 27 public void run() { 28 boolean control = true; 29 int i =0; 30 while(control ) { 31 System.out.println(">>>>>"); 32 i++; 33 if(i>3) control = false; 34 } 35 } 36 }); 37 } 38 }View Code
2、实现方式-懒汉模式+双重校验锁

1 package com.learn.designpattern.singleton; 2 3 import java.util.concurrent.ArrayBlockingQueue; 4 import java.util.concurrent.ExecutorService; 5 import java.util.concurrent.ThreadPoolExecutor; 6 import java.util.concurrent.TimeUnit; 7 8 /** 9 * 10 * @author zhujj 11 */ 12 13 public class ThreadPoolUntil { 14 15 private static volatile ThreadPoolUntil threadPoolUntil; 16 17 private ThreadPoolUntil() { 18 // TODO Auto-generated constructor stub 19 } 20 21 public static ThreadPoolUntil getIntance() { 22 if(threadPoolUntil==null) { 23 synchronized(ThreadPoolUntil.class) { 24 if(threadPoolUntil==null) { 25 threadPoolUntil = new ThreadPoolUntil(); 26 } 27 } 28 } 29 return threadPoolUntil; 30 } 31 }View Code
推荐使用方式一

更多精彩