Give a question, as follows:
The solution is as follows:
1 Public classDemo_5 {2 3 Public Static voidMain (string[] args) {4 //Create a window5Ticketwindow tw1=NewTicketwindow ();6 7 //start at the same time with three threads8Thread t1=NewThread (TW1);9Thread t2=NewThread (TW1);TenThread t3=NewThread (TW1); One A T1.start (); - T2.start (); - T3.start (); the } - - } - + //Ticket window class - classTicketwindowImplementsrunnable{ + Private intnums=2000;//Altogether 2000 tickets A at @Override - Public voidrun () { - while(true){ - - if(nums>0) {//decide if there's a ticket . - //Thread.CurrentThread (). GetName () Gets the name of the current thread inSystem.out.println (Thread.CurrentThread (). GetName () + "in the sale of the" +nums+ "ticket");//Show Ticketing Information - to //The speed of the ticket is one second out. + Try { -Thread.Sleep (1000); the}Catch(interruptedexception e) { * e.printstacktrace (); $ }Panax Notoginseng -nums--; the}Else{ + Break;//Ticket End A } the + } - } $}
The problem with executing this code is that the same ticket number may be sold by multiple ticket windows, and the code of the trouble is the if Else statement block.
The workaround is to use synchronized (Object) {The code you want to synchronize} in the code snippet that needs to be synchronized.
The modified code is as follows:
1 Public classDemo_5 {2 3 Public Static voidMain (string[] args) {4 //Create a window5Ticketwindow tw1=NewTicketwindow ();6 7 //start at the same time with three threads8Thread t1=NewThread (TW1);9Thread t2=NewThread (TW1);TenThread t3=NewThread (TW1); One A T1.start (); - T2.start (); - T3.start (); the } - - } - + //Ticket window class - classTicketwindowImplementsrunnable{ + Private intnums=2000;//Altogether 2000 tickets A at @Override - Public voidrun () { - while(true){ - //consider the If else code to guarantee its atomicity (synchronous block of code) - synchronized( This) { - in if(nums>0) {//decide if there's a ticket . - //Thread.CurrentThread (). GetName () Gets the name of the current thread toSystem.out.println (Thread.CurrentThread (). GetName () + "in the sale of the" +nums+ "ticket");//Show Ticketing Information + - //The speed of the ticket is one second out. the Try { *Thread.Sleep (1000); $}Catch(interruptedexception e) {Panax Notoginseng e.printstacktrace (); - } the +nums--; A}Else{ the Break;//Ticket End + } - $ } $ } - } -}
Execute this code to find out the ticket is OK.
Thread 1 is executing code that needs to be synchronized, thread 2,3,4......blocked, being put into a thread waiting pool, as if someone had closed the door (locked) before going to the toilet, and then came out (unlocked), and then others could continue to use it.
How to troubleshoot thread safety issues in Java