There may be deadlocks in too many synchronizations, and deadlocks can occur only when the program is running.
In multi-threaded sharing of resources, synchronization is required, but too much synchronization can cause deadlocks.
Deadlock Example:
Packagecom.vince;/*** Thread Deadlock *@authorAcer **/ Public classDeadthreaddemo { Public Static voidMain (string[] args) {NewDeadthread (); }}//Customerclasscustomer{ Public synchronized voidSay (Waiter W) {System.out.println ("The customer said, eat first, pay the bill."); W.doservice (); } Public synchronized voidDoservice () {System.out.println ("Yes, I'll buy you a meal."); }}//Waiterclasswaiter{ Public synchronized voidsay (Customer c) {System.out.println ("The waiter said," pay for dinner first. "); C.doservice (); } Public synchronized voidDoservice () {System.out.println ("Yes, I'll pay you after dinner."); }}//Deadlock ThreadclassDeadthreadImplementsrunnable{Customer C=NewCustomer (); Waiter W=NewWaiter (); PublicDeadthread () {NewThread ( This). Start (); W.say (c); } Public voidrun () {C.say (w); } }
Example of a thread break:
Packagecom.vince;/*** Interrupt Thread, custom mark *@authorAcer **/ Public classThreaddemo { Public Static voidMain (string[] args) {MyThread Mt=NewMyThread (); Thread T1=NewThread (MT); T1.start (); //t1.stop ();//Stop for(inti=0;i<10;i++){ Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); }} Mt.flag=false; } Static classMyThreadImplementsrunnable{ Public BooleanFlag; PublicMyThread () {flag=true; } Public voidrun () {intI=0; while(flag) {System.out.println ("I=" +i); Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } I++; if(i==100) Break;//Exit Loop } } }}
Java Multi-Threading and concurrency--deadlock and interrupt threads