Demonstration of deadlock in multiple threads

Source: Internet
Author: User

Demonstration of deadlock in multiple threads

Package com. huowolf;/* deadlock meaning: * multiple threads are blocked at the same time, and one or all of them are waiting for the release of a resource. * The program cannot run properly because the thread is blocked indefinitely. ** Deadlock: Nested synchronization in synchronization. * But it may also be harmonious ** A common rule of thumb to avoid deadlocks is: * when several threads need to access Shared resources A, B, and C, ensure that each thread accesses them in the same order. * for example, access A first and access B and C. * // Deadlock example: class Test implements Runnable {private boolean flag; public Test (boolean flag) {this. flag = flag;} @ Overridepublic void run () {if (flag) {while (true) {synchronized (MyLock. locka) {System. out. println ("if locka"); synchronized (MyLock. lockb) {System. out. println ("if lockb") ;}}} else {while (true) {synchronized (MyLock. lockb) {System. out. println ("else lockb"); synchronized (MyLock. locka) {System. out. println ("else locka") ;}}}} class MyLock {static Object locka = new Object (); static Object lockb = new Object ();} public class DeadLockTest {public static void main (String [] args) {Thread t1 = new Thread (new Test (true )); thread t2 = new Thread (new Test (false); t1.start (); t2.start ();}}

Related Article

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.