1. 程式人生 > >單例的實現--靜態內部類

單例的實現--靜態內部類

 1 package com.redis.threadpool;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 import java.util.concurrent.ArrayBlockingQueue;
 6 import java.util.concurrent.ExecutorService;
 7 import java.util.concurrent.Executors;
 8 
 9 /**
10  * @Author zhangliwei
11  * @Date 2018/11/13 下午3:39
12 * 單例的實現有很多種 13 * 靜態內部類的方式,絕對執行緒安全的 14 */ 15 public class RequestProcessThreadPool { 16 17 private ExecutorService threadPool = Executors.newFixedThreadPool(10); 18 /** 19 * 記憶體佇列 20 */ 21 private List<ArrayBlockingQueue<Request>> queues = new ArrayList<>();
22 23 public RequestProcessThreadPool() { 24 for (int i = 0; i < 10; i++) { 25 ArrayBlockingQueue<Request> arrayBlockingQueue = new ArrayBlockingQueue<>(100); 26 queues.add(arrayBlockingQueue); 27 threadPool.submit(new WorkerThread(queues));
28 29 } 30 } 31 32 /** 33 * 單例的實現有很多種 34 * 靜態內部類的方式,絕對執行緒安全的 35 */ 36 private static class Singleton{ 37 38 private static RequestProcessThreadPool instance; 39 40 static { 41 instance = new RequestProcessThreadPool(); 42 } 43 44 public static RequestProcessThreadPool getInstance(){ 45 46 return instance; 47 } 48 } 49 50 /** 51 * jvm的機制去保證多執行緒併發安全 52 * 靜態內部類的方式,去初始化單例 53 * @return 54 */ 55 public static RequestProcessThreadPool getInstance(){ 56 return Singleton.getInstance(); 57 } 58 59 public void init(){ 60 getInstance(); 61 } 62 63 }

 

 1 package com.imooc.schoolproject.zookeeper;
 2 
 3 /**
 4  * @Author zhangliwei
 5  * @Date 2018/11/20 下午8:22
 6  * 單例模式獲取zookeeper
 7  */
 8 public class ZookeeperSession {
 9 
10     public static class Singleton{
11         
12         private static ZookeeperSession singleton;
13 
14         static {
15             singleton = new ZookeeperSession();
16         }
17 
18         public static ZookeeperSession getInstance(){
19             return singleton;
20         }
21     }
22 
23     public static ZookeeperSession getZookeeperInstance(){
24         return Singleton.getInstance();
25     }
26 
27     public static void init(){
28         getZookeeperInstance();
29     }
30 }