博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
单例和多线程
阅读量:4476 次
发布时间:2019-06-08

本文共 1566 字,大约阅读时间需要 5 分钟。

 要保证在多线程环境下的单例模式,有下面两种建议的方式:

一、静态内部类

public class Singletion {        private static class InnerSingletion {        private static Singletion single = new Singletion();    }        public static Singletion getInstance(){        return InnerSingletion.single;    }    }

 

 二、double check的方式

public class DubbleSingleton {    private static DubbleSingleton ds;        public  static DubbleSingleton getDs(){        if(ds == null){            try {                //模拟初始化对象的准备时间...                Thread.sleep(3000);            } catch (InterruptedException e) {                e.printStackTrace();            }            synchronized (DubbleSingleton.class) {                if(ds == null){                    ds = new DubbleSingleton();                }            }        }        return ds;    }        public static void main(String[] args) {        Thread t1 = new Thread(new Runnable() {            @Override            public void run() {                System.out.println(DubbleSingleton.getDs().hashCode());            }        },"t1");        Thread t2 = new Thread(new Runnable() {            @Override            public void run() {                System.out.println(DubbleSingleton.getDs().hashCode());            }        },"t2");        Thread t3 = new Thread(new Runnable() {            @Override            public void run() {                System.out.println(DubbleSingleton.getDs().hashCode());            }        },"t3");                t1.start();        t2.start();        t3.start();    }    }

 

转载于:https://www.cnblogs.com/dongdone/p/5727402.html

你可能感兴趣的文章
East Brother Video Indoor Monitor
查看>>
Python基础数据类型2
查看>>
linux Shell脚本编码格式
查看>>
【转】人脸表情识别综述
查看>>
【转】OpenCV图像处理 图像的点运算 ( 灰度直方图 )
查看>>
斜率优化DP学习笔记
查看>>
vim 操作命令大全(转)
查看>>
<C++>CLR必须定义入口点
查看>>
TFS自动记住用户名密码 免密码自动登录
查看>>
Leetcode-290 Word Pattern(单词模式)
查看>>
搜索输入框提示--输入延迟,仿自动脑学院
查看>>
COM, COM+ and .NET 的区别
查看>>
【读书笔记】iOS-网络-应用间通信
查看>>
【读书笔记】iOS-工作区的使用
查看>>
ASP.NET Web API 2 入门(一)
查看>>
yum安装mongodb
查看>>
PHP基础知识系列:拦截器方法
查看>>
confluece安装文档及破解
查看>>
解决SpringCloud使用Feign跨服调用时header请求头中的信息丢失
查看>>
《CoffeeScript应用开发》学习:第五章 CoffeeScript中的类
查看>>