Package Test.access.foreign;public class Foreign {public static void main (String args[]) {MyThread mt=new MyThread (); int i=0;i<20;i++)//Simulate 20 ticket terminal new Thread (MT). Start (); /** * Print Results: */}class MyThread implements Runnable{int tacket=5, @Overridepublic Void Run () {try {sale ();} catch (Interrupte Dexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Private synchronized void sale () throws Interruptedexception{long Time= (Long) (Math.random () *5000); SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "hibernate" +time+ "milliseconds"); Thread.Sleep (time);//Analog Network delay if (tacket>=1) {System.out.println ("Ticket:" +tacket--);} Else{system.out.println ("no Ticket");}}}
Way two:
Package Test.access.foreign;public class Foreign {public static void main (String args[]) {MyThread mt=new MyThread (); int i=0;i<20;i++)//Simulate 20 ticket terminal new Thread (MT). Start (); /** * Print Result: */}class MyThread implements Runnable{int tacket=5; @Overridepublic void Run () {try {synchronized (this) {Long ti Me= (Long) (Math.random () *5000); SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "hibernate" +time+ "milliseconds"); Thread.Sleep (time);//Analog Network delay if (tacket>=1) {System.out.println ("Ticket:" +tacket--);} Else{system.out.println ("no Ticket");}}} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Two ways of thread synchronization