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

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

【线程死锁】 

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

代码模拟:

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】

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

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

以上是 Java 线程死锁的问题解决办法 的全部内容, 来源链接: utcz.com/p/215811.html

回到顶部