Java 线程死锁的问题解决办法

时间:2022-01-11 13:20:15

 java 线程死锁的问题解决办法

【线程死锁】 

原因:两个线程相互等待被对方锁定的资源

代码模拟:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class deadlock {
  public static void main(string[] args) {
    object obj = new object();
    object obj1 = new object();
    deadlockthread1 d1 = new deadlockthread1(obj, obj1);
    deadlockthread2 d2 = new deadlockthread2(obj, obj1);
    new thread(d1,"线程1").start();
    new thread(d2,"线程2").start();
  }
}
 
class deadlockthread1 implements runnable {
  private object obj;
  private object obj1;
 
  public deadlockthread1(object obj, object obj1) {
    this.obj = obj;
    this.obj1 = obj1;
  }
 
  @override
  public void run() {
    synchronized (obj) {   //deadlockthread1锁定obj对象
      try {
        thread.sleep(1000);
        synchronized (obj1) { //等待锁定obj1对象,obj对象已被deadlockthread2锁定
          obj1.getclass();
        }
      } catch (interruptedexception e) {
        e.printstacktrace();
      }
    }
  }
}
 
class deadlockthread2 implements runnable {
  private object obj;
  private object obj1;
 
  public deadlockthread2(object obj, object obj1) {
    this.obj = obj;
    this.obj1 = obj1;
  }
 
  @override
  public void run() {
    synchronized (obj1) {   //deadlockthread2锁定obj2对象
      try {
        thread.sleep(1000);
        synchronized (obj) { //等待锁定obj对象,obj对象已被deadlockthread1锁定
          obj.getclass();
        }
      } catch (interruptedexception e) {
        e.printstacktrace();
      }
    }
  }
}

查看方式:

1、【cmd】下输入【jconsole】

Java 线程死锁的问题解决办法

2、选择测试线程并点击右下角【连接】,左上角选择【线程】,左下角选择【检测死锁】

Java 线程死锁的问题解决办法

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望通过本文能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/rickiyeat/article/details/52558047