首页 > 代码库 > 单例模式
单例模式
- package com.jdjinsui.controlservice.tool;
- import com.activemq.PSession;
- import com.activemq.model.*;
- import com.activemq.p2p.Productor;
- import javax.jms.DeliveryMode;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * Created by zxy on 2017/5/11.
- */
- public class activeMQProducer {
- // 定义一个私有构造方法
- private activeMQProducer() {
- }
- //定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)
- private static volatile activeMQProducer instance;
- //定义一个共有的静态方法,返回该类型实例
- public static activeMQProducer getIstance() {
- // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率)
- if (instance == null) {
- //同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)
- synchronized (activeMQProducer.class) {
- //未初始化,则初始instance变量
- if (instance == null) {
- instance = new activeMQProducer();
- }
- }
- }
- return instance;
- }
- public static String test() {
- String str = null;
- activeMQProducer aa = activeMQProducer.getIstance();
- activeMQProducer bb = activeMQProducer.getIstance();
- if (aa.equals(bb)) {
- str = "相同";
- } else {
- str = "不同";
- }
- return str;
- }
- }
单例模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。