The reason for the deadlock is generally the two-object lock waiting for each other.
In the article "Java Thread: Thread synchronization and lock", the concept and simple example of deadlock are briefly described, but the given example is incomplete, and here is a complete example.
/**
* Java Thread: Concurrent collaboration-Deadlock
*
* @author Administrator
*/
public class Test {
public static void Main (string[] args) {
Deadlockrisk Dead = new Deadlockrisk ();
mythread t1 = new Mythread (dead, 1, 2);
mythread t2 = new Mythread (dead, 3, 4);
mythread t3 = new Mythread (dead, 5, 6);
mythread t4 = new Mythread (dead, 7, 8);
T1.start ();
T2.start ();
T3.start ();
T4.start ();
}
}
class Mythread extends Thread {
Private Deadlockrisk dead;
private int A, b;
Mythread (Deadlockrisk dead, int a, int b) {
this.dead = dead;
THIS.A = A;
this.b = b;
}
@Override
public void Run () {
Dead.read ();
Dead.write (A, b);
}
}
class Deadlockrisk {
private Static class Resource {
public int value;
}
private Resource Resourcea = new Resource ();
private Resource Resourceb = new Resource ();
public int Read () {
synchronized (resourcea) {
System.out.println ("Read ():" + Thread.CurrentThread (). GetName () + "Get Resourcea lock!" ");
synchronized (RESOURCEB) {
System.out.println ("Read ():" + Thread.CurrentThread (). GetName () + "Get RESOURCEB lock!" ");
return resourceb.value + resourcea.value;
}
}
}
public void Write (int a, int b) {
synchronized (RESOURCEB) {
System.out.println ("Write ():" + Thread.CurrentThread (). GetName () + "Get Resourcea lock!" ");
synchronized (resourcea) {
System.out.println ("Write ():" + Thread.CurrentThread (). GetName () + "Get RESOURCEB lock!" ");
Resourcea.value = A;
resourceb.value = b;
}
}
}
}
The following deadlock occurred, it is really rare to see AH:
Source: http://lavasoft.blog.51cto.com/62575/222074