首页 > 其他 > 详细

设计模式之单例模式>>应用场景及实现

时间:2019-04-21 17:28:03      阅读:474      评论:0      收藏:0      [点我收藏+]

定义

单例模式(Singleton),也叫单子模式,是一种常用的软件设计模式。对于系统而言该实例有且仅有一个。

应用场景

线程池、数据库池、用于对系统做初始化的实例,提供给关联系统调用的接口(任务提交部分)

不适用成员变量多变的场景。

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

推荐使用方式一

 

设计模式之单例模式>>应用场景及实现

原文:https://www.cnblogs.com/zhujj1314/p/10741077.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!