您好,登錄后才能下訂單哦!
Java deadlock生成的示例分析,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
Java deadlock生成需要我們注意的關鍵點有很多,其實有不少的問題都能在源代碼中尋找到不少的答案。下面我們就看看如何才能更好的做出Java deadlock生成。
public class Deadlock extends Object ...{ private String objID; public Deadlock(String id) ...{ objID = id; } public synchronized void checkOther(Deadlock other) ...{ print("entering checkOther()"); // simulate some lengthy process try ...{ Thread.sleep(2000); } catch (InterruptedException x) ...{ } print("in checkOther() - about to " + "invoke 'other.action()'"); other.action(); print("leaving checkOther()"); } public synchronized void action() ...{ print("entering action()"); // simulate some work here try ...{ Thread.sleep(500); } catch (InterruptedException x) ...{ } print("leaving action()"); } public void print(String msg) ...{ threadPrint("objID=" + objID + " - " + msg); } public static void threadPrint(String msg) ...{ String threadName = Thread.currentThread().getName(); System.out.println(threadName + ": " + msg); } public static void main(String[] args) ...{ final Deadlock obj1 = new Deadlock("obj1"); final Deadlock obj2 = new Deadlock("obj2"); Runnable runA = new Runnable() ...{ public void run() ...{ obj1.checkOther(obj2); } }; Thread threadA = new Thread(runA, "threadA"); threadA.start(); try ...{ Thread.sleep(200); } catch (InterruptedException x) ...{ } Runnable runB = new Runnable() ...{ public void run() ...{ obj2.checkOther(obj1); } }; Thread threadB = new Thread(runB, "threadB"); threadB.start(); try ...{ Thread.sleep(5000); } catch (InterruptedException x) ...{ } threadPrint("finished sleeping"); threadPrint("about to interrupt() threadA"); threadA.interrupt(); try ...{ Thread.sleep(1000); } catch (InterruptedException x) ...{ } threadPrint("about to interrupt() threadB"); threadB.interrupt(); try ...{ Thread.sleep(1000); } catch (InterruptedException x) ...{ } threadPrint("did that break the deadlock?"); } }
以上就是對Java deadlock生成的詳細介紹,希望大家能有所領悟。
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。