IDEA 多线程调试单例模式

一、准备条件

1. 代码

package com.zhang.pattern.singleton;

/**
 * 单例模式:饿汉-不考虑线程安全
 */
public class LazySimpleSingleton {
    private LazySimpleSingleton() {
    }

    private static LazySimpleSingleton instance;

    public static LazySimpleSingleton getInstance() {
        if (instance == null) {
            instance = new LazySimpleSingleton();
        }
        return instance;
    }
}

2. 测试代码

package com.zhang.pattern;

import com.zhang.pattern.singleton.LazySimpleSingleton;
import org.junit.Test;

public class LazySimpleSingletonTest {
    @Test
    public void testLazySimpleSingleton() {
        Thread thread1 = new Thread(() -> System.out.println(Thread.currentThread().getName() + ": " + LazySimpleSingleton.getInstance()));
        Thread thread2 = new Thread(() -> System.out.println(Thread.currentThread().getName() + ": " + LazySimpleSingleton.getInstance()));
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            System.out.println("caught InterruptedException, ignore it");
        }
    }
}

二、Debug调试

1. 打断点,将断点设置为Tread模式

右键单击断点,即可设置,勾选Thread

2. 开始调试 

点击Debug开始调试:

程序在断点处停下来了,我们选择Thread-0,然后进入if语句内部:

然后切换到Thread-1,直接运行结束:

然后切换到Thread-0,也运行结束,就得到了以下结果:

好,以上就是IDEA在多线程环境下,测试懒汉式单例模式线程安全的示范,供大家参考,欢迎留言评论!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值