First, the type of ticket robbery:
Package Cn.jbit.ticket;public class Ticket implements Runnable {private int num = 0;//number of votes private int count = 10;//number of votes left Boolean flag = false; @Overridepublic void Run () {while (true) {//when there is no residual ticket, jump out of the loop if (count <= 0) {break;} Num++;count--;try {thread.sleep (500);//analog Network delay} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Show ticketing Information:" + thread.currentthread (). GetName () + "grab the first" + num + "ticket, remaining" + Count + "Ticket");}} }
Second, the test class:
Package Cn.jbit.ticket;public class Test {/** * @param args */public static void main (string[] args) {ticket ticket=new Ti Cket ();//Instantiate several Rob users thread mary = new Thread (ticket, "Mary"); Thread jack = new Thread (ticket, "Jack"); Mary.start (); Jack.start ();}}
Code that does not use thread synchronization results in the following: multiple people will grab the same ticket .
With thread synchronization, the code looks like this:
Package Cn.jbit.ticket;public class Ticket implements Runnable {private int num = 0;//number of votes private int count = 10;//number of votes left Boolean flag = false; @Overridepublic void Run () {while (true) {synchronized (this) {////without a residual ticket, jump out of the loop if (count <= 0) {break ;} Num++;count--;try {thread.sleep (500);//analog Network delay} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Show ticket info:" + thread.currentthread (). GetName () + "grab the first" + num + "ticket, remaining" + Count + "Ticket");}} }
The effect is as follows:
multithreaded analog network in Java grab ticket code