单例模式之懒汉式线程不安全的测试代码

单例模式的懒汉式是线程不安全的,下面给出测试代码,使用的是Callable和FutureTask实现的

public class SingletonTest03 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("懒汉式,线程不安全的");
        //下面通过Callable接口和FutureTask来实现
        Callable<Singleton> singletonCallable = () -> {
            Singleton singleton=Singleton.getInstance();
            return singleton;
        };
        Callable<Singleton> singletonCallable1 = () -> {
            Singleton singleton=Singleton.getInstance();
            return singleton;
        };
        FutureTask<Singleton> ft = new FutureTask<>(singletonCallable);
        FutureTask<Singleton> ft1 = new FutureTask<>(singletonCallable1);
        new Thread(ft).start();
        new Thread(ft1).start();
        Singleton singleton = ft.get();
        Singleton singleton1 = ft1.get();
        System.out.println(singleton1==singleton);
    }
}
class Singleton {
    private static Singleton instance;
    private Singleton() {
    }
    //提供一个静态的公有方法,当使用到该方法时,才会去创建instance
    //即懒汉式
    //如果要改成线程安全的懒汉式,只需要在下面方法的static后面添加synchronized字段即可
    //public static synchronized Singleton getInstance() {
    public static Singleton getInstance() {
        if (instance == null) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            instance = new Singleton();
        }
        return instance;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值