Java中数据同步-synchronized关键字与Mointor的使用:
Java中数据同步-synchronized关键字与Mointor的使用_霸道流氓气质的博客-CSDN博客
上面简单介绍synchronized的使用,如果在IDEA中怎样对多线程的程序进行调试,
比如分别对单个线程进行断点调试,当第一个线程执行到synchronized时验证是否会
上锁,然后再调试另一个线程,是否还能再进入。
注:
博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
1、首先实现一个懒汉式单例模式的示例类
- package com.ruoyi.demo.designPattern.lazySimpleSingleton;
-
- /**
- * 懒汉式单例模式:被外部类调用时内部类才会加载
- */
- public class LazySimpleSingleton {
-
- private static LazySimpleSingleton lazySimpleSingleton = null;
-
- private LazySimpleSingleton(){}
- //静态块,公共内存区域
- public static LazySimpleSingleton getInstance(){
- if(lazySimpleSingleton == null){
- synchronized(LazySimpleSingleton.class){
- if(lazySimpleSingleton == null){
- lazySimpleSingleton = new LazySimpleSingleton();
- }
- }
- }
- return lazySimpleSingleton;
- }
- }
2、然后写一个线程类ExecutorThread
- package com.ruoyi.demo.designPattern.lazySimpleSingleton;
-
- public class ExecutorThread implements Runnable{
-
- @Override
- public void run() {
- LazySimpleSingleton simpleSingleton = LazySimpleSingleton.getInstance();
- System.out.println(Thread.currentThread().getName()+":"+simpleSingleton);
- }
- }
3、客户端测试代码如下
- package com.ruoyi.demo.designPattern.lazySimpleSingleton;
-
- public class LazySimpleSingletonTest {
- public static void main(String[] args) {
- Thread t1 = new Thread(new ExecutorThread());
- Thread t2 = new Thread(new ExecutorThread());
- t1.start();
- t2.start();
- System.out.println("结束");
- }
- }
4、这种情况如何在IDEA中进行断点调试,并验证两个线程在同时进入synchnorized时的表现
用线程模式调试
先给ExecutorThread类打上断点,鼠标右键单击断点,切换为Thread模式

然后给LazySimpleSingleton类同样打上断点并设置为Thread,这里在进入getInstacne方法和进入synchronized时分别打上断点

给客户端测试代码同样也打上断点,同样改为Thread模式

开始debug后,可以在debug控制台切换Thread并分别进行调试

5、先选中线程0,使其进入到synchronized中,此时会进行上锁,然后再切换到线程1,此时1再执行到
synchronized时就会变成MONITOR状态,出现堵塞。直到进程0执行完,进程1才恢复到RUNNING状态。
