Multithreading in Java (iii)

Source: Internet
Author: User

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)

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.