Java死锁分析
程序员文章站
2022-04-18 14:36:22
...
Java死锁分析
1、什么叫死锁(性能等待)?
答:简单的说,就是线程互 相等待
2、范例演示
Dead.java的内容如下所示
public class DeadLock {
final Object lockA = new Object();
final Object lockB = new Object();
public static void main(String[] args) {
DeadLock demo = new DeadLock();
demo.startLock();
}
public void startLock(){
ThreadA a= new ThreadA(lockA,lockB);
ThreadB b= new ThreadB(lockA,lockB);
//start threads
a.start();
b.start();
}
}
class ThreadA extends Thread{
private Object lockA = null;
private Object lockB = null;
public ThreadA(Object a, Object b){
this.lockA = a;
this.lockB = b;
}
public void run() {
synchronized (lockA) {
System.out.println("*** Thread A: ***: Lock A" );
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB) {
System.out.println("*** Thread A: ***: Lock B" );
}
}
System.out.println("*** Thread A: ***: Finished" );
}
}
class ThreadB extends Thread{
private Object lockA = null;
private Object lockB = null;
public ThreadB(Object a, Object b){
this.lockA = a;
this.lockB = b;
}
public void run() {
synchronized (lockB) {
System.out.println("*** Thread B: ***: Lock B" );
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockA) {
System.out.println("*** Thread B: ***: Lock A" );
}
}
System.out.println("*** Thread B: ***: Finished" );
}
}
在Linux上执行java程序
编译程序:javac DeadLock.java
执行程序:java DeadLock
JDK:提供强大的性能诊断工具 Thread Dump文本信息 照片对性能照片
快捷键
windows:组合键ctrl+break == ctrl+fn+bLinux:kill -3 pid
一下为截取的日志信息
Java stack information for the threads listed above:
===================================================
"Thread-1":
at ThreadB.run(DeadLock.java:68)
- waiting to lock <0x000000076dc57420> (a java.lang.Object)
- locked <0x000000076dc57430> (a java.lang.Object)
"Thread-0":
at ThreadA.run(DeadLock.java:41)
- waiting to lock <0x000000076dc57430> (a java.lang.Object)
- locked <0x000000076dc57420> (a java.lang.Object)
Found 1 deadlock.