To solve this problem, a program becomes in the waiting state (deadlock) due to resource occupation and resource competition ).
Solve this problem:
We can add a "Lock" to the resource to determine the status of the current lock before each call, and then execute.
The following is a simulation program:
Package com. yxy. thread; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock; import java. util. random;/*** @ author windows * security lock example */public class Safelock {/*** @ author windows * Friend entity class */static class Friend {// Friend class, lock (re-entry lock) private final String name; private final Lock lock = new ReentrantLock (); // Friend constructor public Friend (String name) {this. name = name;} // obtain the name publ Ic String getName () {return this. name;} // judge public boolean impendingBow (Friend bower) before bowing {// current my status lock and Boolean myLock = false; boolean yourLock = false; try {// record the lock of the current class, and the lock status of the friend of the bow. myLock = lock. tryLock (); yourLock = bower. lock. tryLock ();} finally {// if the current class is locked, it is in the state of the class with the bow friend. if (! (MyLock & yourLock) {// determines that the lock is in the true status and is unlocked. If (myLock) {lock. unlock ();} if (yourLock) {bower. lock. unlock () ;}}// return result return myLock & yourLock ;}/ ***** @ param bower * method of bowing to a Friend */public void bow (Friend bower) {// determine whether there is a lock if (impendingBow (bower) {// when a friend bows, I do not bow. Print the information and return to you. Try {System. out. format ("% s: % s has" + "bowed to me! % N ", this. name, bower. getName (); bower. bowBack (this);} finally {lock. unlock (); bower. lock. unlock () ;}} else {// when a friend bows, I also bow. Print the information. System. out. format ("% s: % s started" + "to bow to me, but saw that" + "I was already bowing to" + "him. % n ", this. name, bower. getName () ;}}/*** @ param bower * method of bowing. */Public void bowBack (Friend bower) {System. out. format ("% s: % s has" + "bowed back to me! % N ", this. name, bower. getName () ;}}/*** @ author windows * loop bowing thread */static class BowLoop implements Runnable {// two private Friend bower; private Friend bowee; // constructor public BowLoop (Friend bower, Friend bowee) {this. bower = bower; this. bowee = bowee;} // The thread's execution method public void run () {Random random = new Random (); for (;) {// infinite loop. Try {// process interrupt Thread. sleep (random. nextInt (5);} catch (InterruptedException e) {}// bowee bowed bowee to bower. bow (bower) ;}}// test public static void main (String [] args) {final Friend alphonse = new Friend ("Alphonse "); final Friend gaston = new Friend ("Gaston"); new Thread (new BowLoop (alphonse, gaston )). start (); new Thread (new BowLoop (gaston, alphonse )). start ();}}