单例模式

  1. package com.jdjinsui.controlservice.tool;
  2. import com.activemq.PSession;
  3. import com.activemq.model.*;
  4. import com.activemq.p2p.Productor;
  5. import javax.jms.DeliveryMode;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. /**
  9. * Created by zxy on 2017/5/11.
  10. */
  11. public class activeMQProducer {
  12. // 定义一个私有构造方法
  13. private activeMQProducer() {
  14. }
  15. //定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)
  16. private static volatile activeMQProducer instance;
  17. //定义一个共有的静态方法,返回该类型实例
  18. public static activeMQProducer getIstance() {
  19. // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率)
  20. if (instance == null) {
  21. //同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)
  22. synchronized (activeMQProducer.class) {
  23. //未初始化,则初始instance变量
  24. if (instance == null) {
  25. instance = new activeMQProducer();
  26. }
  27. }
  28. }
  29. return instance;
  30. }
  31. public static String test() {
  32. String str = null;
  33. activeMQProducer aa = activeMQProducer.getIstance();
  34. activeMQProducer bb = activeMQProducer.getIstance();
  35. if (aa.equals(bb)) {
  36. str = "相同";
  37. } else {
  38. str = "不同";
  39. }
  40. return str;
  41. }
  42. }

posted on 2017-05-15 11:07  幻影鬼火  阅读(88)  评论(0编辑  收藏  举报

导航