Java Multi thread deadlock
The main causes of deadlocks are:
- Because of insufficient system resources.
- The order in which the process is running is inappropriate.
- Improper allocation of resources.
If the system has sufficient resources, the resource requests of the process can be met, the likelihood of deadlocks is very low, otherwise it will be locked into a deadlock because of the contention for limited resources. Secondly
The process can run in a different order and speed, and may also generate deadlocks.
The four necessary conditions for creating a deadlock:
- Mutex Condition: A resource can only be used by one process at a time.
- request and hold condition: When a process is blocked by a request for resources, it remains in place for the resources that have been obtained.
- Non-deprivation: The resources that the process has acquired cannot be forcibly stripped until the end of use.
- cyclic wait condition: A cyclic waiting resource relationship is formed between several processes.
These four conditions are necessary for the deadlock, as long as the system has a deadlock, these conditions must be established, and as long as one of the above conditions is not satisfied, there will be no deadlock.
Example:
Package Com.lock;public class Test implements Runnable {public int flag = 1;static Object obj1 = new Object (), obj2 = new Object ();p ublic void Run () {System.out.println ("flag=" + flag), if (flag = = 1) {synchronized (obj1) {try {Thread.Sleep (500 );} catch (Interruptedexception e) {e.printstacktrace ();} Synchronized (OBJ2) {System.out.println ("1");}} if (flag = = 0) {synchronized (obj2) {try {thread.sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Synchronized (obj1) {System.out.println ("0");}}} public static void Main (string[] args) {Test TD1 = new Test (); Test TD2 = new test (); td1.flag = 1;td2.flag = 0; thread T1 = new Thread (TD1); Thread t2 = new Thread (TD2); T1.start (); T2.start ();}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java multi-thread----thread deadlock