1 PackageShb.java.demo;2 /**3 * Multithreaded test sell ticket applet. 4 * @Package: Shb.java.demo5 * @Description:6 * @authorshaobn7 * @Date 2015-9-2 pm 7:49:538 */9 Public classTestsyn {Ten Public Static voidMain (string[] args) { One //This annotation is implemented as a A /*Ticketdemo td = New Ticketdemo (); - thread T1 = new Thread (TD); - thread t2 = new Thread (TD); the T1.start (); - T2.start ();*/ - //to achieve the way two -TicketDemo2 TD2 =NewTicketDemo2 (); +Thread t3 =NewThread (TD2); -Thread T4 =NewThread (TD2); + T3.start (); A T4.start (); at } - } - /** - * Class of ticket sales (Implementation mode one) - * @Package: Shb.java.demo - * @Description: in * @authorshaobn - * @Date 2015-9-2 pm 7:44:45 to */ + classTicketdemoImplementsrunnable{ - Private intTicket = 200; the Public voidrun () { * while(true){ $ synchronized( This){Panax Notoginseng if(ticket>0){ - Try { theThread.Sleep (100); +}Catch(Exception e) { A //Todo:handle Exception the e.printstacktrace (); + } -System.out.println (Thread.CurrentThread () + "* * *" + "number of votes" +ticket--); $ } $ } - } - } the - }Wuyi /** the * Class of ticket selling (Implementation Mode II) - * @Package: Shb.java.demo Wu * @Description: - * @authorShihaobin About * @Date 2015-9-2 pm 7:51:56 $ */ - classTicketDemo2Implementsrunnable{ - Public intTicket = 200; - Public voidrun () { A while(true){ + Show (); the } - } $ //enabling encapsulation of multi-threaded threads the Public synchronized voidShow () { the if(ticket>0){ the Try { theThread.Sleep (100); -}Catch(Exception e) { in //Todo:handle Exception the e.printstacktrace (); the } AboutSystem.out.println (Thread.CurrentThread () + "* * *" + "number of votes" +ticket--); the } the the } +}
A simple mock-up that uses multithreading to sell tickets.
Java Multi-threaded implementation of the ticket sales program