/* Multi-threaded security issues
1. Why are there security issues?
Because the program is running, a thread will be eligible for execution after judging the condition, but no code is running
The latter thread also judged the condition and was qualified for execution, and the latter thread ran the code, but at this point the thread ran out of condition that it did not meet the
At this point, there's a security problem.
2. Methods that implement interface threads cannot throw exceptions!
*/
/* Operating condition
Through analysis, found that print out 0,-1,-2 and other wrong votes.
A security issue occurs with multi-threaded operation
The cause of the problem?
When multiple statements share data on the same thread, one of the threads executes only a portion of the statement, and it has not finished executing
Another thread is involved, resulting in a shared data error
Solutions
Statements that share data on multiple operations can only have one thread complete. During execution, other threads do not participate in the execution.
Java provides a professional solution for multi-threaded security issues
is to synchronize the code block
Format:
Synchronized (object) object can be arbitrary (use God on the line)
{
Code that needs to be synchronized (which code is sharing data in action)
}
*/
Class Ticket implements Runnable//extends Thread
{
Object Obj=new object ();
private static int tick=100;
public void Run ()
{
while (true)
{synchronized (obj)
{
if (tick>0)
{
Try
{
Thread.Sleep (10); /* Sleep a bit every time you run */
}
catch (Exception e)
{
}
System.out.println (Thread.CurrentThread (). GetName () + "sale:--" +tick--);
}
}
}
}
}
Class Ticketdemo
{
public static void Main (String args[])
{
Ticket t=new Ticket ();
Thread t1=new thread (t);
Thread t2=new thread (t);
Thread t3=new thread (t);
Thread t4=new thread (t);
T1.start ();
T2.start ();
T3.start ();
T4.start ();
}
}
Java Multi-Threading security issues