• 单例模式


     1 package zzuli.acmen.sigleton;
    2
    3 /**
    4 * 单例模式,顾名思义也就是整个程序中只有这么一个实例,这样的有什么用处呢?也就是用在通常的只需要一个实例,每一次都是调用一个的
    5 * 以下实现的是用户的连接数的统计,可以用在工厂模式里面,因为里面的工厂都是只有一个对象!
    6 * @author Acmen
    7 *
    8 */
    9 public class Singleton {
    10 /*
    11 * 第一种实现方法
    12 */
    13
    14 // private static Singleton sinleton = new Singleton();
    15 //
    16 // private Singleton(){}
    17 //
    18 // public static Singleton getSin(){
    19 //
    20 // return sinleton;
    21 //
    22 // }
    23 //
    24 /*
    25 * 第二中实现方法
    26 */
    27
    28 private static Singleton singleton = null;
    29
    30 private Singleton(){}
    31
    32 //记住必须加前面的那个 synchronized 为什么自己体会
    33 public static synchronized Singleton getSin(){
    34
    35 if(singleton == null)
    36 singleton = new Singleton();
    37 return singleton;
    38
    39 }
    40
    41 private int i;
    42
    43 public synchronized void add(){
    44
    45 i++;
    46 System.out.println("现在的数目是"+i);
    47
    48 }
    49
    50 }
     1 package zzuli.acmen.sigleton;
    2
    3 public class Main {
    4
    5 /**
    6 * @param args
    7 */
    8 //测试用例
    9 public static void main(String[] args) {
    10
    11 for(int i=0;i<100;i++){
    12 new Thread(new Runnable() {
    13
    14 public void run() {
    15 Singleton sin = Singleton.getSin();
    16 sin.add();
    17
    18 }
    19 }).start();
    20
    21
    22 }
    23
    24 }
    25
    26 }



  • 相关阅读:
    myeclipse关掉references
    eclipse/myeclipse SVN资源库URL中文乱码问题解决办法
    获取登录用户ip
    MySQL高级 之 explain执行计划详解(转)
    代码部署工具walle(一)
    mongodb备份策略
    nginx报错整理
    记一次java程序占用cpu超高排查
    HDFS恢复误删操作的方法
    有趣的工具
  • 原文地址:https://www.cnblogs.com/Acmen/p/2365474.html
Copyright © 2020-2023  润新知