Spring(三)多线程下的单例的几种方式

都是通过例子来介绍

1.饿汉单例(简单的说就是一上来就创建对象)

先创建一个单例的类MySingleton

package demo01;

/**
 * Created by mycom on 2018/3/6.
 */
public class MySingleton {
    private static MySingleton instance = new MySingleton();

    private MySingleton(){}

    public static MySingleton getInstance() {
        return instance;
    }
}

在编写线程类,并且测试

package demo01;

/**
 * Created by mycom on 2018/3/6.
 */
public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println(MySingleton.getInstance().hashCode());
    }

    public static void main(String[] args) {

        MyThread[] mts = new MyThread[10];
        for(int i = 0 ; i < mts.length ; i++){
            mts[i] = new MyThread();
        }

        for (int j = 0; j < mts.length; j++) {
            mts[j].start();
        }
    }
}

如果运行的结果所有的都是一样的,说明实验成功,

2.懒汉单例(用到的时候才会创建对象)

线程安全的---方法中声明synchronized关键字

package demo01;

/**
 * Created by mycom on 2018/3/6.
 */
public class MySingleton {
    private static MySingleton instance = null;

    private MySingleton(){}

    public synchronized static MySingleton getInstance() {
        try {
            if(instance != null){//懒汉式

            }else{
                //创建实例之前可能会有一些准备性的耗时工作
                Thread.sleep(300);
                instance = new MySingleton();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return instance;
    }
}
package demo01;

/**
 * Created by mycom on 2018/3/6.
 */
public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println(MySingleton.getInstance().hashCode());
    }

    public static void main(String[] args) {

        MyThread[] mts = new MyThread[10];
        for(int i = 0 ; i < mts.length ; i++){
            mts[i] = new MyThread();
        }

        for (int j = 0; j < mts.length; j++) {
            mts[j].start();
        }
    }
}

3.使用静态内置类实现单例模式(对上面MySingleton的代码进行改动)

package demo01;

/**
 * Created by mycom on 2018/3/6.
 */
public class MySingleton {
    //内部类
    private static class MySingletonHandler{
        private static MySingleton instance = new MySingleton();
    }

    private MySingleton(){}

    public static MySingleton getInstance() {
        return MySingletonHandler.instance;
    }
}

测试结果

。。。。。。。

 

转载于:https://www.cnblogs.com/my-123/p/8512313.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值