1. About deadlock
Deadlock, we can simply understand that two threads use the same resource at the same time, and the two threads do not get the corresponding resources, resulting in no waiting for each other.
2. simulate a deadlock
Background: we create a friend class. When a friend bows to us, we also bow to our friends. This is a complete action. When two
While bowing, waiting for the other party to bow. A deadlock occurs.
Simulation Program:
Package com. yxy. thread; /*** @ author windows * Deadlock Simulation Program */public class Deadlock {/*** @ author windows * Friend entity class */static class Friend {// Friend name private final string name; // construct a Friend object type public Friend (String name) {this. name = name;} // obtain the public String getName () {return this. name ;}// a Friend bows to me (synchronous) public synchronized void bow (Friend bower) {System. out. format ("% s: % s" + "has bowed to me! % N ", this. name, bower. getName (); bower. bowBack (this);} // method of bowing (synchronous) public synchronized void bowBack (Friend bower) {System. out. format ("% s: % s" + "has bowed back to me! % N ", this. name, bower. getName () ;}} public static void main (String [] args) {// deadlock simulation program test start // create two friends alphonse, gaston final Friend alphonse = new Friend ("Alphonse"); final Friend gaston = new Friend ("Gaston"); // start the thread of two friends bowing. New Thread (new Runnable () {public void run () {alphonse. bow (gaston );}}). start (); new Thread (new Runnable () {public void run () {gaston. bow (alphonse );}}). start ();}}