This article mainly introduces relevant information on how to solve the problem of Java thread deadlock. I hope this article can help everyone and solve similar problems. Friends in need can refer to it
Java thread deadlock problem solution
[Thread deadlock]
Cause: Two threads are waiting for each other to be locked by the other party Resources
Code simulation:
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(); } } } }
View method:
1. Enter [jconsole] under [cmd] ]
#2. Select the test thread and click [Connect] in the lower right corner, select [Thread] in the upper left corner, and select [Detect Deadlock] in the lower left corner
The above is the detailed content of Solutions to thread deadlock problems in Java. For more information, please follow other related articles on the PHP Chinese website!