/**
* @author Liangjun
* @descriptionTODO
* Alphonse Gaston two objects waiting for each other to release a lock , Thread Blocking , cause a deadlock
*/
Public class Friend {
Private final String name;
Public Friend (String name) {
this. name = name;
}
Public String GetName () {
return this. name;
}
Public synchronized void bow (Friend bower) {
System. out. Format ("%s:%s"
+ "have bowed to me!%n",
this. name, Bower.getname ());
Bower.bowback (this);
}
Public synchronized void bowback (friendbower) {
System. out. Format ("%s:%s"
+ "have bowed back to me!%n",
this. name, Bower.getname ());
}
Public static void main (string[] args) {
Final Friend alphonse =
New Friend ("Alphonse");
Final Friend Gaston =
New Friend ("Gaston");
New Thread (new Runnable () {
Public void run () {Alphonse.bow (Gaston);}
}). Start ();
New Thread (new Runnable () {
Public void run () {Gaston.bow (Alphonse);}
}). Start ();
}
}
/**
* @author Liangjun
* @descriptionTODO
* 1. multiple threads of the same object are called separately method1 method2 when ,
* 2.ThreadA Get lock lock_1,threadb Get Lock_2,
* 3.ThreadA continue to perform the acquisition lock_2 when, or threadb continue to perform the acquisition Lock_1 when , Lock_2/lock_1 were possessed by each other,
* 4.THREADA/THREADB thread blocking, causing a deadlock phenomenon
*
*/
class Deadlocker {
int field_1;
Private Objectlock_1 =newint[1];
int field_2;
Private Objectlock_2 =newint[1];
Public void method1 (int value) {
synchronized (lock_1) {
Try {
Thread. Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System. out. println (" current thread:" + thread. ) CurrentThread(). GetName ());
synchronized (lock_2) {
field_1 = 0;
field_2 = 0;
System. out. println ("method1");
}
}
}
Public void method2 (int value) {
synchronized (lock_2) {
System. out. println (" current thread:" + thread. ) CurrentThread(). GetName ());
synchronized (lock_1) {
field_1 = 0;
field_2 = 0;
System. out. println ("method2");
}
}
}
Public static void main (String args[]) {
Final Deadlocker dl =new deadlocker ();
New Thread (new Runnable () {
@Override
Public void run () {
DL.METHOD1 (0);
}
}). Start ();
New Thread (new Runnable () {
@Override
Public void run () {
DL.METHOD2 (1);
}
}). Start ();
}
}
/**
* solution: Have all threads get a set of locks in the same order
* make multiple locks into one group and place them under the same lock
*/
Java common thread blocking and solutions