Solution to multi-thread deadlock

Source: Internet
Author: User

Public class deadlock implements runnable {private Boolean flag; Private Static final object O1 = new object (); Private Static final object O2 = new object (); @ overridepublic void run () {string threadname = thread. currentthread (). getname (); system. out. println (threadname + ": Flag =" + flag); If (flag = true) {synchronized (O1) {try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (threadname + "Enter synchronization for O1 prepare to enter daily O2");/* will cause deadlock synchronized (O2) {system. out. println (threadname + "synchronization block O2");} * // solve the deadlock // synchronized (O2) {system. out. println (threadname + "synchronization block O2"); // }}} if (flag = false) {synchronized (O2) {try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (threadname + "Synchronize to O2 to prepare to enter O1"); synchronized (O1) {system. out. println (threadname + "synchronization block O1") ;}}} public static void main (string [] ARGs) {deadlock d1 = new deadlock (); deadlock D2 = new deadlock (); d1.flag = true; d2.flag = false; new thread (D1 ). start (); New thread (D2 ). start ();}}

When an object has not been released in the thread synchronization lock and another synchronization lock cannot obtain resources (the resource order used is the opposite), a deadlock may occur.

Solution 1: for exampleCodeTo cancel a synchronization lock

Solution 2: do not cancel, but use the same resource sequence.

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.