每天一例多线程[day12]-----单例模式与线程安全

 

package com.jeff.base.conn011;

  1.  
  2. public class DubbleSingleton {

  3.  
  4. private static DubbleSingleton ds;

  5.  
  6. public static DubbleSingleton getDs(){

  7. if(ds == null){

  8. try {

  9. //模拟初始化对象的准备时间...

  10. Thread.sleep(3000);

  11. } catch (InterruptedException e) {

  12. e.printStackTrace();

  13. }

  14. synchronized (DubbleSingleton.class) {

  15. if(ds == null){

  16. ds = new DubbleSingleton();

  17. }

  18. }

  19. }

  20. return ds;

  21. }

  22.  
  23. public static void main(String[] args) {

  24. Thread t1 = new Thread(new Runnable() {

  25. @Override

  26. public void run() {

  27. System.out.println(DubbleSingleton.getDs().hashCode());

  28. }

  29. },"t1");

  30. Thread t2 = new Thread(new Runnable() {

  31. @Override

  32. public void run() {

  33. System.out.println(DubbleSingleton.getDs().hashCode());

  34. }

  35. },"t2");

  36. Thread t3 = new Thread(new Runnable() {

  37. @Override

  38. public void run() {

  39. System.out.println(DubbleSingleton.getDs().hashCode());

  40. }

  41. },"t3");

  42.  
  43. t1.start();

  44. t2.start();

  45. t3.start();

  46. }

  47.  
  48. }

 
  1. package com.jeff.base.conn011;

  2.  
  3. public class Singletion {

  4.  
  5. private static class InnerSingletion {

  6. private static Singletion single = new Singletion();

  7. }

  8.  
  9. public static Singletion getInstance(){

  10. return InnerSingletion.single;

  11. }

  12.  
  13.  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值