Java Tread Multithreading (3) deadlock

Source: Internet
Author: User

Author: Ching

Original address: http://blog.csdn.net/qingdujun/article/details/39367655


This article demonstrates, tread multi-threaded deadlock, simple analysis of the cause of the deadlock, and show a deadlock of the small demo.

1) Cause of deadlock

2) Small Demo


One, the cause of the deadlock: Synchronization in a nested synchronization.

Second Deadlock small demo: (lock Loacka need to lock lockb, lock lockb also need to lock locka, and then add while (true) in the inside a crazy turn, directly locked. )

Package NO.ZUO.NO.DIE;//1. Implement Runnable Interface class Zuosi implements Runnable{private Boolean flag; Zuosi (Boolean f) {flag = f;} 2. Override the Run method public void run () {if (flag) {while (true) {synchronized (Clock.locka) {System.out.println ("if Locka"); Synchronized (clock.lockb) {System.out.println ("if lockb");}}} else {while (true) {synchronized (clock.lockb) {System.out.println ("Else lockb"); synchronized (Clock.locka) { System.out.println ("Else Locka");}}}}} It contains 2 Locks class Clock{static Object Locka = new Object (); static object lockb = new Object ();} public class Cdeadlock {public static void main (string[] args) {//3. Create 2 threads thread T1 = new Thread (new Zuosi (true)); Thread t2 = new Thread (new Zuosi (false)),//4. Boot thread T1.start (); T2.start ();}}
Run the display result (Is it dead?) It's locked!!! ):


References: Java video Bi Xiangdong presenter

Original address: http://blog.csdn.net/qingdujun/article/details/39367655


Java Tread Multithreading (3) deadlock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.