"code example" a simple Java deadlock

Source: Internet
Author: User

in the actual programming, to avoid the occurrence of deadlock, but some interviews deliberately let you write a deadlock program, it seems not too simple (some companies will have such an interview), the following is a simple deadlock example.

Code Description:

The first step : whenDeadLockthe Thread objectTD1of the PropertiesFlagto be1, the first thread locks a resource firstO1,Sleeping -milliseconds, and then try to lock the resourceO2(if not locked);
Step Two:while the first thread is sleeping, the second thread objectTD2started, its propertiesFlagto be0, it locks Resources firstO2, and then sleep -milliseconds to try to lock the resourceO1, but at this point the first thread has locked the resourceO1, it can only wait;

The result of these two steps is:
* T1 Sleep After the end of the need to lock O2 to continue execution, and at this time O2 has been T2 locked;
* T2 Sleep After the end of the need to lock O1 to continue execution, and at this time O1 has been T1 locked;
* T1, T2 wait for each other, both need the other lock resources to continue execution, thereby deadlock.

Class DeadLock implements Runnable {public int flag = 1;static Object O1 = new Object (), O2 = new Object (); @Overridepublic void Run () {System.out.println ("flag=" + flag), if (flag = = 1) {synchronized (O1) {try {thread.sleep ($);} catch (Excepti On e) {e.printstacktrace ();} Synchronized (O2) {System.out.println ("1");}} if (flag = = 0) {synchronized (O2) {try {thread.sleep];} catch (Exception e) {e.printstacktrace ();} Synchronized (O1) {System.out.println ("0");}}} public static void Main (string[] args) {DeadLock TD1 = new DeadLock ();D eadlock td2 = new DeadLock (); td1.flag = 1;td2.flag = 0;new Thread (TD1). Start (); new Thread (TD2). Start ();}}

"code example" a simple Java 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.