Java 线程死锁的问题解决办法
程序员文章站
2024-03-02 19:19:04
java 线程死锁的问题解决办法
【线程死锁】
原因:两个线程相互等待被对方锁定的资源
代码模拟:
public clas...
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、选择测试线程并点击右下角【连接】,左上角选择【线程】,左下角选择【检测死锁】
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望通过本文能帮助到大家,谢谢大家对本站的支持!