Java Multi-Threading security issues

Source: Internet
Author: User
Tags ticket

/* 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.