Java Multi-Threading and concurrency--deadlock and interrupt threads

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.