When we use thread synchronization, we may have deadlocks when we use threads, and the cause of the deadlock is:
Cases:
Two classes each have two methods, and these four kinds of release synchronization, such as customer and waiter to solve the "first payment or after payment" problem, will generate deadlock.
Deadlock-generated conditions:
Mutex conditions
Request hold Condition
Non-deprivation conditions
Loop wait
Causes of deadlocks:
Improper resource competition and process sequence promotion
Code:
1 PackageThreaddemo;2 3 //a synchronous method that invokes another object in a synchronous method may result in a deadlock4 //dead Lock5 Public classThreadDemo7 {6 Public Static voidMain (string[] args) {7 NewDeadthread ();8 }9 }Ten One classDeadthreadImplementsrunnable{ ACustomer C =NewCustomer (); -Waiter W =Newwaiter (); - PublicDeadthread () { the NewThread ( This). Start (); - W.say (c); - } - @Override + Public voidrun () { - //TODO auto-generated Method Stub + C.say (w); A } at } - - //Customer - classcustomer{ - Public synchronized voidSay (Waiter W) { -SYSTEM.OUT.PRINTLN ("Customer says: Eat before you Pay"); in W.doservice (); - } to Public synchronized voidDoservice () { +System.out.println ("Buy a meal and eat again"); - } the } * classwaiter{ $ Public synchronized voidsay (Customer c) {Panax NotoginsengSYSTEM.OUT.PRINTLN ("Waiter says: Pay first and eat again"); - C.doservice (); the } + Public synchronized voidDoservice () { ASystem.out.println ("Pay after Dinner"); the } +}
Thread deadlock problem in Java