In order to solve the program because of resources, there is a scramble for resources, and the resulting program into the waiting state (deadlock).
To address this problem:
We can add a "lock" to the resource, determine the status of the current lock before each call, and then execute.
The following is an emulator:
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 * Friends entity class * * * stat
IC class Friend {//friend class, lock (re-lock) private final String name;
Private Final lock lock = new Reentrantlock ();
Friend construct method public friend (String name) {this.name = name;
//Gets the name public String GetName () {return this.name; ///Before bowing judgment public boolean impendingbow (friend Bower) {//Current my state lock, with friend's state lock Boolean myl
Ock = false;
Boolean Yourlock = false;
try {//Record the lock of the current class, and the state of the lock of the bowing friend MyLock = Lock.trylock ();
Yourlock = Bower.lock.tryLock (); finally {//if the current class is locked, with a bow friend's class state, where there is a false if (!) (MyLock && yourLock)) {//The judge is the one whose state is true to unlock the lock.
if (myLock) {lock.unlock ();
} if (Yourlock) {bower.lock.unlock ();
}}//Return results MyLock && Yourlock;
/** * @param Bower * The way to bow to friends * * public void bow (friend Bower) { Determine if there is a lock if (Impendingbow (bower)) {//friend bowed when I did not bow.
Print out the information and return it.
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 {//friends bow while I bow.
Print out the information. System.out.format ("%S:%s started "+" to bow to me, but saw that "+" I am already bowing to "
+ "him.%n", THIS.name, Bower.getname ());
}/** * @param bower * The method of bowing. */public void Bowback (Friend bower) {System.out.format ('%s:%s has ' + ' bowed back t
o me!%n ", this.name, Bower.getname ()); }/** * @author windows * Loop bowed thread/static class Bowloop implements Runnable {//bow to each other
Two persons private Friend bower;
Private Friend Bowee;
Construction method Public Bowloop (friend Bower, friend Bowee) {this.bower = bower;
This.bowee = Bowee;
//thread execution method public void run () {Random Random = new Random (); for (;;)
{//infinite loop. try {//process interrupt THREAD.SLEep (Random.nextint (5));
The catch (Interruptedexception e) {}//bowee bowed to the Bower Bowee.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 ();
}
}