Java死锁的例子
1、一个Java死锁的程序
public class DeadLock {
private String A = "A";
private String B = "B";
public static void main(String[] args) {
new DeadLock().deadLock();
}
private void deadLock() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (A) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (B) {
System.out.println("Thread t1");
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (B) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (A) {
System.out.println("Thread t2");
}
}
}
});
t1.start();
t2.start();
}
}
2、编译运行Java程序
[root@cent01 javatest]# javac DeadLock.java
[root@cent01 javatest]# java DeadLock
3、利用 jps 查看当前的Java程序
[root@cent01 ~]# jps
2672 Jps
2661 DeadLock
4、利用 jstack 查看死锁信息
[root@cent01 ~]# jstack 2661
Found one Java-level deadlock:
=============================
"Thread-1":
waiting to lock monitor 0x092cba78 (object 0xa1847358, a java.lang.String),
which is held by "Thread-0"
"Thread-0":
waiting to lock monitor 0x092cadd0 (object 0xa1847380, a java.lang.String),
which is held by "Thread-1"
Java stack information for the threads listed above:
===================================================
"Thread-1":
at DeadLock$2.run(DeadLock.java:42)
- waiting to lock <0xa1847358> (a java.lang.String)
- locked <0xa1847380> (a java.lang.String)
at java.lang.Thread.run(Thread.java:745)
"Thread-0":
at DeadLock$1.run(DeadLock.java:24)
- waiting to lock <0xa1847380> (a java.lang.String)
- locked <0xa1847358> (a java.lang.String)
at java.lang.Thread.run(Thread.java:745)
Found 1 deadlock.
还没有评论,来说两句吧...