1 Packagecom.test;2 3 Public classSaleticketsImplementsRunnable4 {5 Private intTicketcount = 10;//total number of votes6Object Mutex =NewObject ();//Lock7 8 /**9 * Ticket salesTen */ One Public voidSellticket () A { - synchronized(mutex)//when you are working with shared data, - //surround it with a synchronous block of code so that only one thread executes the contents of the synchronized code block at execution time the { - if(Ticketcount > 0) - { -ticketcount--; + System.out.println (Thread.CurrentThread (). GetName () -+ "Selling tickets, remaining" + Ticketcount + "Ticket"); + } A Else at { -System.out.println ("The tickets are sold out!") "); - return; - } - } - } in - Public voidRun () to { + while(Ticketcount > 0)//a loop is a thread that keeps selling tickets. - { the Sellticket (); * /** $ * In the synchronization code block sleep, and not sleep effect is the same, the role is only self-executing, do not let the thread executePanax Notoginseng * So put the sleep outside the sync code block, so sell a ticket to sleep for a while, so that the other threads to sell, so that all the threads can sell tickets - */ the Try + { AThread.Sleep (100); the } + Catch(interruptedexception e) - { $ e.printstacktrace (); $ } - } - } the}
Here is the call
1 Packagecom.test;2 3 Public classTicketmain4 {5 6 Public Static voidMain (string[] args)7 {8Saletickets Runticekt =Newsaletickets ();9Thread Th1 =NewThread (Runticekt, "Window 1");TenThread Th2 =NewThread (Runticekt, "Window 2"); OneThread Th3 =NewThread (Runticekt, "Window 3"); AThread Th4 =NewThread (Runticekt, "Window 4"); - Th1.start (); - Th2.start (); the Th3.start (); - Th4.start (); - } - +}
Execution effect:
Examples of Java multi-threaded ticket sales