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