這篇文章主要介紹了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(); } } } }# 檢視方式:
以上是Java中關於線程死鎖的問題解決方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!