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 name
Public String getName (){
Return this. name;
}
// A friend bowed his way 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 );
}
// I bow back (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 ){
// Test the deadlock simulation program
// Create two friends, alphonse and Gaston
Final Friend alphonse =
New Friend ("Alphonse ");
Final Friend gaston =
New Friend ("Gaston ");
// Start the thread of two friends.
New Thread (new Runnable (){
Public void run () {alphonse. bow (gaston );}
}). Start ();
New Thread (new Runnable (){
Public void run () {gaston. bow (alphonse );}
}). Start ();
}
}