In the actual programming, in order to avoid the deadlock situation, however, to let you write a useful program deadlock seems almost not too simple (kind of interview questions), below is a simple deadlock example.
Synchronization of threads can cause deadlocks, and deadlocks occur when two of threads hold each other's waiting items (actually, something that is shared by two threads). Just having two threads and two objects can create a deadlock.
Package sxh.java.lock;/*** a simple deadlock class * When Deadlock Class object Flag==1 (TD1), lock O1 First, sleep 500 milliseconds * while TD1 in sleep there is a Flag==0 object (TD2) thread started, Lock O2 First, sleep 500 milliseconds * TD1 after the end of sleep need to lock O2 talent continue to run, while O2 has been td2 locked. * TD2 sleep After the end of the need to lock O1 talent continue to run. And at this time O1 has been td1 locked, * TD1, TD2 each other to wait, all need to get the other party locked resources talent continue to run, thereby deadlock. */public class DeadLock implements Runnable {public int flag = 1;//Static object is a private static objects shared by all objects of the class O1 = new Object (), O2 = new Object (), @Overridepublic Void Run () {System.out.println ("flag=" + flag), if (flag = = 1) {synchronized (O1) {try {T Hread.sleep (500);} catch (Exception 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;//td1,td2 are all in a running state, but it is not certain which thread the JVM thread is scheduled to run first.TD2 's Run () may run the new thread (TD1) before TD1 Run (). Start (); new Thread (TD2). Start ();}}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
A simple example of Java deadlock Demo