这篇文章主要介绍了 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、选择测试线程并点击右下角【连接】,左上角选择【线程】,左下角选择【检测死锁】
Atas ialah kandungan terperinci Java中关于线程死锁的问题解决办法. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!