A security issue occurs with multi-threaded operation
Reason:
When multiple statements operate on the same thread data, a thread executes only a portion of the multiple statements, not yet finished
Another thread participates in the execution, causing the error to share the data
Workaround:
Statements that share data on multiple operations can only have one thread complete. During execution, other threads are not allowed to participate in execution.
Java provides a professional solution for multithreading security issues
is to synchronize the code block
Synchronized (object)
{
Code that needs to be synchronized
}
1 classTicketImplementsRunnable//extends Thread2 {3 Private intTick = 100;4Object obj =NewObject ();5 Public voidRun ()6 {7 while(true)8 {9 synchronized(obj)Ten { One if(tick>0) A { - Try{Thread.Sleep (10);}Catch(Exception e) {} -System.out.println (Thread.CurrentThread (). GetName () + "Sales:" +tick--); the } - } - } - } + } - classDemo + { A at Public Static voidMain (string[] args) - { -Ticket T =NewTicket (); -Thread T1 =NewThread (t); -Thread t2 =NewThread (t); -Thread t3 =NewThread (t); inThread T4 =NewThread (t); - T1.start (); to T2.start (); + T3.start (); - T4.start (); the /* * Ticket t1 = new Ticket (); $ Ticket t2 = new Ticket ();Panax Notoginseng Ticket t3 = new Ticket (); - T1.start (); the T2.start (); + T3.start (); A */ the //System.out.println (""); + } -}View Code
Multithreading in Java (iii)