共计 1717 个字符,预计需要花费 5 分钟才能阅读完成。
什么是死锁
死锁问题是多线程特有的问题,它能够被认为是线程间切换耗费零碎性能的一种极其状况。在死锁时,线程间互相期待资源,而又不开释本身的资源,导致无穷无尽的期待,其后果是零碎工作永远无奈执行实现。死锁问题是在多线程开发中应该坚定防止和杜绝的问题.
死锁示例代码
package com.rumenz.learn.deadLock;
public class RumenzThread implements Runnable{
int a,b;
public RumenzThread(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public void run() {//Integer.valueOf(a) 包装成对象
synchronized (Integer.valueOf(a)){
try{
// 睡眠 3 秒, 减少死锁的几率
Thread.sleep(3000);
}catch (Exception e){e.printStackTrace();
}
synchronized (Integer.valueOf(b)){System.out.println("a+b="+(a+b));
}
}
}
}
package com.rumenz.learn.deadLock;
public class DeadLock {public static void main(String[] args) {new Thread(new RumenzThread(1, 2)).start();
new Thread(new RumenzThread(2, 1)).start();}
}
运行程序应用 jstack -l pid
来定位死锁
先找到死锁程序的过程 id
> jps
56993 Jps
56636 Launcher
57066 DeadLock // 这个就是死锁的过程
应用 jstack -l 57066
来定位死锁
> jstack -l 57066
Found one Java-level deadlock:
=============================
"Thread-1":
waiting to lock monitor 0x00007fbe6d80de18 (object 0x000000076ab33988, a java.lang.Integer),
which is held by "Thread-0"
"Thread-0":
waiting to lock monitor 0x00007fbe6d8106a8 (object 0x000000076ab33998, a java.lang.Integer),
which is held by "Thread-1"
Java stack information for the threads listed above:
===================================================
"Thread-1":
at com.rumenz.learn.deadLock.RumenzThread.run(RumenzThread.java:27)
- waiting to lock <0x000000076ab33988> (a java.lang.Integer)
- locked <0x000000076ab33998> (a java.lang.Integer)
at java.lang.Thread.run(Thread.java:748)
"Thread-0":
at com.rumenz.learn.deadLock.RumenzThread.run(RumenzThread.java:27)
- waiting to lock <0x000000076ab33998> (a java.lang.Integer)
- locked <0x000000076ab33988> (a java.lang.Integer)
at java.lang.Thread.run(Thread.java:748)
Found 1 deadlock. // 发现一个死锁
RumenzThread.java:27
定位到大略的代码文件地位。
jconsole
定位死锁问题
- 找到死锁过程
- 链接, 不平安的链接
- 抉择线程
- 点击检测死锁
关注微信公众号:【入门小站】, 解锁更多知识点。
正文完