博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
通过编程发现Java死锁
阅读量:5740 次
发布时间:2019-06-18

本文共 3976 字,大约阅读时间需要 13 分钟。

通过stack也可以发现死锁。

测试类

import java.util.concurrent.TimeUnit;public class Test {    public static void main(String[] args) {        DeadlockDetector deadlockDetector = new DeadlockDetector(new DeadlockConsoleHandler(), 5, TimeUnit.SECONDS);        deadlockDetector.start();        final Object lock1 = new Object();        final Object lock2 = new Object();        Thread thread1 = new Thread(()->{            synchronized (lock1) {                System.out.println("Thread1 acquired lock1");                try {                    TimeUnit.MILLISECONDS.sleep(500);                } catch (InterruptedException ignore) {                }                synchronized (lock2) {                    System.out.println("Thread1 acquired lock2");                }            }        });        thread1.start();        Thread thread2 = new Thread(()->{            synchronized (lock2) {                System.out.println("Thread2 acquired lock2");                synchronized (lock1) {                    System.out.println("Thread2 acquired lock1");                }            }        });        thread2.start();    }}

处理类

public class DeadlockConsoleHandler implements DeadlockHandler {    @Override    public void handleDeadlock(final ThreadInfo[] deadlockedThreads) {        if (deadlockedThreads != null) {            System.err.println("Deadlock detected!");            Map
stackTraceMap = Thread.getAllStackTraces(); for (ThreadInfo threadInfo : deadlockedThreads) { if (threadInfo != null) { for (Thread thread : Thread.getAllStackTraces().keySet()) { if (thread.getId() == threadInfo.getThreadId()) { System.err.println(threadInfo.toString().trim()); for (StackTraceElement ste : thread.getStackTrace()) { System.err.println("t" + ste.toString().trim()); } } } } } } }}import java.lang.management.ThreadInfo;public interface DeadlockHandler { void handleDeadlock(final ThreadInfo[] deadlockedThreads);}

关键类

import java.lang.management.ManagementFactory;import java.lang.management.ThreadInfo;import java.lang.management.ThreadMXBean;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class DeadlockDetector {    private final DeadlockHandler deadlockHandler;    private final long period;    private final TimeUnit unit;    private final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);    final Runnable deadlockCheck = new Runnable() {        @Override        public void run() {            long[] deadlockedThreadIds = mbean.findDeadlockedThreads();            if (deadlockedThreadIds != null) {                ThreadInfo[] threadInfos = mbean.getThreadInfo(deadlockedThreadIds);                deadlockHandler.handleDeadlock(threadInfos);            }        }    };    public DeadlockDetector(final DeadlockHandler deadlockHandler, final long period, final TimeUnit unit) {        this.deadlockHandler = deadlockHandler;        this.period = period;        this.unit = unit;    }    public void start() {        this.scheduler.scheduleAtFixedRate(this.deadlockCheck, this.period, this.period, this.unit);    }}

测试结果

Thread1 acquired lock1Thread2 acquired lock2Deadlock detected!"Thread-1" Id=12 BLOCKED on java.lang.Object@6a80bb83 owned by "Thread-0" Id=11ttest.Test.lambda$main$1(Test.java:32)ttest.Test$$Lambda$2/363771819.run(Unknown Source)tjava.lang.Thread.run(Thread.java:745)"Thread-0" Id=11 BLOCKED on java.lang.Object@6ebf220b owned by "Thread-1" Id=12ttest.Test.lambda$main$0(Test.java:23)ttest.Test$$Lambda$1/668386784.run(Unknown Source)tjava.lang.Thread.run(Thread.java:745)Deadlock detected!

 

转载地址:http://fwbzx.baihongyu.com/

你可能感兴趣的文章
ⅰsee是什么意思_安氏分类ⅠⅡⅢ,你的牙齿是哪类
查看>>
bable怎么使用 eclipse_Java Web轻松学46 - Maven集成到Eclipse中
查看>>
flex 换主轴后子元素占满_Flex布局,真香!
查看>>
机器人 知乎碧桂园_碧桂园机器人首降淮阳,助力城市文化旅游
查看>>
ae2020不支持的视频驱动程序_音视频PaaS平台基于Windows的抓屏技术
查看>>
图纸打印什么时候用蓝图_工程图纸为什么是蓝图?
查看>>
网页中竖的目录怎么改成横的_骨架隔墙怎么做?
查看>>
查看历史操作记录_git操作方法
查看>>
5怎么选国外节点_房子装修,床垫怎么选?这5家床垫值得买
查看>>
变成一列_Excel一列数据转多行多列,这4条函数公式可以学起来
查看>>
手机超广角拍摄软件_如何用超广角“看开一点”?OPPO官方教学,这些大片装下整个夏天...
查看>>
rip协议中周期性广播路由信息的报文_关于RIP的一点小笔记--华为
查看>>
linux oracle无法解析指定的连接标识符_pl/sql连接oracle时候,提示无法解析指定的连接标识符...
查看>>
webstorm如何编写jsp_WebStorm中怎样运行JSP页面在浏览器中显示
查看>>
python自动填日志_python接口自动化(四十)- logger 日志 - 下(超详解)
查看>>
python文本可视化数据分析软件_数据探索很麻烦?推荐一款史上最强大的特征分析可视化工具:yellowbrick...
查看>>
python range(30)_python的range()函数
查看>>
windows python3 paramiko安装_Python3.3 Paramiko Windows安装错误
查看>>
ref获取元素 vue 删除子元素_vue 添加删除子元素
查看>>
mysql有回收站吗_mysql 回收站
查看>>