单例的实现--静态内部类
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 }
开启打怪升级之旅