What do you call a deadlock?
The so-called deadlock: refers to two or more than two processes in the execution process, because of the competition for resources caused by a mutual waiting phenomenon, if there is no external force, they will not be able to proceed.
So why would a deadlock occur?
1. Due to insufficient system resources.
2. The sequence in which the process is running is inappropriate.
3. Improper allocation of resources.
The friends who have learned the operating system know: There are four conditions for deadlocks:
1. Mutually exclusive condition: the so-called mutex is the process in a certain time exclusive resources.
2. 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.
3. Conditions of deprivation: the process has acquired resources and cannot be forcibly deprived until the end of its use.
4. Cyclic wait conditions: a cyclic waiting resource relationship is formed between several processes.
For example:
Deadlock is because of the multi-threaded access to shared resources, due to improper access, usually a thread locked a resource A, but also want to lock resource B, and in another thread, the lock resource B, but also to lock resource A to complete its own operations, two threads want the other's resources, Instead of releasing their own resources, two of threads are waiting for a situation that cannot be performed.
Examples of deadlocks are given below
/*** Excessive sync method may cause deadlock * **/ Public classSynDemo03 {/** * @paramargs*/ Public Static voidMain (string[] args) {Object g=NewObject (); Object m=NewObject (); Test T1=NewTest (g,m); Test2 T2=NewTest2 (g,m); Thread Proxy=NewThread (t1); Thread Proxy2=NewThread (T2); Proxy.start (); Proxy2.start (); }}classTestImplementsrunnable{Object goods; Object money; PublicTest (Object goods, object money) {Super(); This. Goods =goods; This. Money =Money ; } @Override Public voidrun () { while(true) {test (); } } Public voidTest () {synchronized(goods) {Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } synchronized(Money) {}} System.out.println ("Money in the Hand"); } }classTest2Implementsrunnable{Object goods; Object money; PublicTest2 (Object goods, object money) {Super(); This. Goods =goods; This. Money =Money ; } @Override Public voidrun () { while(true) {test (); } } Public voidTest () {synchronized(Money) {Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } synchronized(Goods) {}} System.out.println ("A hand to the goods"); } }
Java multithreaded----deadlock