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"