Analog deadlock
Packagecom.gjjun.concurrent;/*** Simulated deadlock, from the art of Java concurrent programming * @Author Gjjun * @Create 2018/8/12 **/ Public classDeadlockdemo {Private StaticString a = "a"; Private StaticString B = "B"; Public Static voidMain (string[] args) {Deadlockdemo Deadlockdemo=NewDeadlockdemo (); Deadlockdemo.deadlock (); } /*** The following code will cause a deadlock, because thread 0 locks a resource, then thread 1 locks the b resource, * After thread 1 calls a resource, but is locked, so wait for a resource to be released, but a resource needs b * resource after 2s, but B resource waits for a resource to release, so form Interdependence. * * You can enter command JPS in the control line to see the class ID, and then use the Jstack ID to see if a deadlock has occurred * * * to avoid deadlocks: * 1. Avoid one thread acquiring multiple locks at the same time. * 2. Avoid a thread that consumes multiple resources at the same time, as much as possible to secure a lock resource. * 3. Try using a timed lock and use Lock.trylock (timeout) instead of * 4. For database locks, lock and unlock must be in a database connection pool. */ Private voidDeadLock () {Thread thread1=NewThread (NewRunnable () {@Override Public voidrun () {synchronized(A) {Try{System.out.println (A); Thread.CurrentThread (); Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } synchronized(B) {System.out.println ("1"); } } } }); Thread thread2=NewThread (NewRunnable () {@Override Public voidrun () {synchronized(B) {Try{System.out.println (B); Thread.CurrentThread (); Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } synchronized(A) {System.out.println ("2"); } } } }); Thread1.start (); Thread2.start (); }}
The following is a deadlock state that is viewed using the Jstack command, where the class file and line number of the deadlock occurred in the red box.
The art record of Java concurrent Programming (i)