您好,登錄后才能下訂單哦!
Java 的死鎖分析
(*)JDK: 提供強大診斷工具:Thread Dump ----> 文本信息
(*)windows: ctrl+break /(fn+B) 打印鎖信息
linux: kill -3 pid ----> 命令:jps 打印鎖信息
Java stack information for the threads listed above:
===================================================
"Thread-1":
at ThreadB.run(DeadLock.java:68)
-waiting to lock <0x244f6498> (a java.lang.Object)
-locked <0x244f64a0> (a java.lang.Object) "Thread-0":
at ThreadA.run(DeadLock.java:41)
-waiting to lock <0x244f64a0> (a java.lang.Object)
-locked <0x244f6498> (a java.lang.Object)
Found 1 deadlock.
代碼如下
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" );
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。