First, the question of the proposed
Take the ticket system for example:
1 classTicketImplementsRunnable2 {3 Public intsum=10;4 Public voidRun ()5 {6 while(true)7 {8 if(sum>0)9 {TenSystem.out.println (Thread.CurrentThread (). GetName () + ":" +sum--); One } A } - } - } the Public classDemo - { - Public Static voidMain (String args[]) - { +Ticket t=NewTicket (); - NewThread (t). Start (); + NewThread (t). Start (); A NewThread (t). Start (); at NewThread (t). Start (); - } -}View Code
There is a problem with this code. Careful analysis can know that if four threads entered the run method at the same time, assuming that the sum==1, then the first thread can enter the if block, but if the CPU suddenly switch to another thread, then the first thread will wait for CPU execution, but does not change the value of sum, At this point the sum is still 1, and the same is true, assuming that the extreme happens, that the 2nd and 3 threads have entered the If block, and both are running before changing the sum value, waiting for the CPU to execute, then the fourth thread changes the value of sum to be called 0, and the remaining three threads change the value of sum to -1,- 2,-3 (but output only to-2), it is obvious that the problem has occurred, although the odds are small, but once the occurrence is a fatal problem.
Use the Thread.Sleep () method to pause the execution of a thread and verify it through the output.
1 classTicketImplementsRunnable2 {3 Public intsum=10;4 Public voidRun ()5 {6 while(true)7 {8 if(sum>0)9 {Ten Try One { AThread.Sleep (50); - } - Catch(Interruptedexception e) {} theSystem.out.println (Thread.CurrentThread (). GetName () + ":" +sum--); - } - - } + } - } + Public classDemo A { at Public Static voidMain (String args[]) - { -Ticket t=NewTicket (); - NewThread (t). Start (); - NewThread (t). Start (); - NewThread (t). Start (); in NewThread (t). Start (); - } to}View Code
Operation Result:
Note exceptions that are generated by using the Sleep method can only be caught that cannot be thrown.
"Java Multithreading security problem Resolution"