Java programming Write a program that causes deadlocks

Source: Internet
Author: User

Threads A and thread B wait for each other to hold a lock that causes the program to loop indefinitely.
Really understand what a deadlock is, this problem is actually not difficult, several steps:
(1) Two threads each hold two object objects: Lock1 and Lock2. These two locks act as the lock of the synchronous code block;
(2) thread 1 of the Run () method in the synchronization code block first get Lock1 object lock, Thread.Sleep (XXX), time does not need too much, 50 milliseconds almost, and then get Lock2 object lock. This is done primarily to prevent thread 1 from starting all at once to obtain an object lock for the Lock1 and Lock2 two objects in a row
(3) thread 2 Run) (method in the synchronous code block first get Lock2 object lock, and then get Lock1 object Lock, of course, then Lock1 object lock has been held by thread 1 lock, thread 2 must be waiting for thread 1 to release Lock1 object lock
in this way, the thread 1″ sleep ", thread 2 has acquired the Lock2 object lock, thread 1 at this time to try to acquire Lock2 object lock, it is blocked, when a deadlock formed

Java programming Write a program that causes deadlocks

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.