Multithreading (understanding of 1_ lock _2_ deadlock analysis)

Source: Internet
Author: User
Tags ticket

We created 4 threads, which, unlike before, used synchronous functions and synchronized code quickly. See how it turns out.

classMlpcImplementsrunnable{Private intTicket = 550;  Public BooleanFlag =true; Object obj=NewObject ();  Public voidrun () {if(Flag = =true)        {             while(true)            {                synchronized (obj) {if(ticket>0)                    {                        if(ticket>0)                        {                                Try{Thread.Sleep (20); }                            Catch(Exception e) {} System.out.println (Thread.CurrentThread ()+ "Show" +ticket--); }                     }                }            }        }        Else        {             while(true) {show (); }        }    }    Public   synchronized void  Show () {if(ticket>0)            {                    Try{Thread.Sleep (20); }                Catch(Exception e) {} System.out.println (Thread.CurrentThread ()+ "Show" +ticket--); }                     }} classMlpcdemo { Public Static voidMain (string[] args) {MLPC m=NewMLPC (); Thread Th0=NewThread (m); Thread Th1=NewThread (m); Thread Th2=NewThread (m); Thread Th3=NewThread (m);        Th0.start (); Try{Thread.Sleep (20); }        Catch(Exception e) {} M.flag=false;        Th1.start ();        Th2.start ();    Th3.start (); }}

The result was a vote of 0.

  Public voidrun () {if(Flag = =true)        {             while(true)            {                synchronized (  This)//change from the original arbitrary object to a functionthe object to which you belongThis  
{ if(ticket>0) { Try{Thread.Sleep (20); } Catch(Exception e) {} System.out.println (Thread.curr Entthread ()+ "Show" +ticket--); } } } } Else { while(true) {show (); } } }

Multithreading (understanding of 1_ lock _2_ deadlock analysis)

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.