"Troubleshooting Thread safety issues: Synchronizing Methods"

Source: Internet
Author: User

Synchronization method: is to add the Sync keyword to the method

What is the lock object for the synchronization method? This (do not believe you can try to change the following this to other objects)

 Packagecom.test; Public classSellticketImplementsRunnable {/**Note that if you are inheriting, you must use static adornments here*/    Private intTickets = 60; Private intx = 0; @Override Public voidrun () { while(true){            if(x%2==0){                synchronized( This) {Dosell (); }            }Else{sellticket (); } x++; }    }    Private synchronized voidSellticket () {Dosell (); }    Private voidDosell () {if(tickets>0){            Try{Thread.Sleep (50); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "+tickets+" is being sold "ticket"); Tickets--; }    }}
 package   com.test;  public  class   selltickettest { public  static  void   main (string[] args)         {sellticket Sellticket  = new   Sellticket ();        Thread T1  = new  Thread (sellticket, "window one"  = new  Thread (sellticket, "window two"  = new  Thread (sellticket, "window three" 

If the static method is synchronous, then the lock object is not this, but the class file.

"Troubleshooting Thread safety issues: Synchronizing Methods"

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.