/*
Deadlock, handwritten deadlock
Conditions of the deadlock formation:
Request to remain
The process has maintained at least one resource, but a new resource request has been made, and the resource is already occupied by other processes. At this point, the process is blocked, but the resource you are getting is kept.
Loop wait
There is a circular wait chain for process resources, and each process in the chain is requested by the next process in the chain.
The non-snatch of resources
The resource acquired by the process cannot be forcibly taken away by another process until it has been used, that is, it can only be freed by the process that acquired the resource. (only active release)
Resource Mutex
A process requires exclusive control over an assigned resource, that is, a resource is owned by only one process at a time, and if another thread requests the resource, the process waits only
Ways to resolve deadlocks:
Prevent deadlocks: Set a limit condition, break a ring into a deadlock or a few conditions to prevent deadlock
Avoid deadlocks: In the allocation of resources, some method is used to prevent the system from entering the unsafe state, thereby avoiding deadlock.
Prevention and release of deadlocks:
*/
public class Deadlock {
public static void Main (string[] args) {
Object O1=new object ();
Object O2=new object ();
Two threads referencing the same object
Thread T1=new Thread (new T1 (O1,O2));
Thread T2=new Thread (new T1 (O1,O2));
T1.start ();
T2.start ();
}
}
New declaration of a like-process class T1
Class T1 implements runnable{
Object O1;
Object O2;
T1 (Object o1,object O2) {
This.o1=o1;
This.o2=o2;
}
@Override
public void Run () {
Synchronized (O1) {//Get lock Object O1
try {
Thread.Sleep (10000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Synchronized (O2) {//Get lock Object O1
}
}
}
}
New declaration of a like-process class T1
Class T2 implements runnable{
Object O1;
Object O2;
T2 (Object o1,object O2) {
This.o1=o1;
This.o2=o2;
}
@Override
public void Run () {
Synchronized (O2) {//Get lock Object O2
try {
Thread.Sleep (10000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Synchronized (O1) {//Get lock Object O1
}
}
}
}