Java------Multithreading: to solve the security problem of multithreading---synchronized synchronous code block

Source: Internet
Author: User

Or an example of a previous ticket sale:


Class Test implements runnable{    private int num =;    Object obj = new Object ();    public void Run ()    {        while (true)        {            if (num >= 0)            {                try                {                    thread.sleep];                }                catch (Exception e)                {                    //Todo:handle exception                    System.out.println (E.tostring ());                }                System.out.println (Thread.CurrentThread (). GetName () + ">>" +num--);}}}    public class runnable{public    static void Main (string[] args)    {        Test t = new Test ();        Thread A = new thread (t);        Thread B = new Thread (t);        Thread c = new Thread (t);        Thread d = new Thread (t);        A.start ();        B.start ();        C.start ();        D.start ();    }}


In the printing results found -1,-2, which is inconsistent with the actual, perhaps you will have doubts, not num >= 0 when the output of the results, why the negative?

This is a multithreaded security issue.

Explain:

When multiple statements are working on the same thread to share data, one thread executes only a portion of the multiple statements, has not finished executing, and another thread participates in the execution, causing the error to share the data.

If you say the output is this:

Thread-2 ... 0

Thread-0...-1

Thread-3...-2

Possible causes of this result are:

When the num=0 0 thread came, slept, 3 threads came, also slept, this time 2 thread sleep time to, woke up, then 2 thread executes the program, the output is 0, then 0 threads and 3 threads woke up, then they then execute the program, do not need to determine whether NUM is eligible, Since they have been judged before they go to sleep, the value of NUM has been turned negative when the result is output. This is why the negative number is output.

Workaround:

Statements that share data on multiple operations can only have one thread complete, and other threads are not allowed to participate during execution.

Solutions for Multithreading: Synchronizing blocks of code

Format:

synchronized (object)
{
Statements that need to be synchronized
}


Solution:


Class Test implements runnable{private int num = 50;    Object obj = new Object (); public void Run () {while (true) {synchronized (obj) {if (num                    ; = 0) {try {thread.sleep (20);                        } catch (Exception e) {//Todo:handle Exception                    System.out.println (E.tostring ());                } System.out.println (Thread.CurrentThread (). GetName () + ">>" +num--); }}}}}public class runnable{public static void Main (string[] args) {Test t = new Te        St ();        Thread A = new thread (t);        Thread B = new Thread (t);        Thread c = new Thread (t);        Thread d = new Thread (t);        A.start ();        B.start ();        C.start ();    D.start (); }}


Which code needs to be synchronized depends on which statements are being manipulated to share the data.


How the synchronous code block works:

Synchronized (obj)

{

Code that is synchronized

}

The code that needs to be synchronized, plus synchronized (obj), is equivalent to closing the code that needs to be synchronized into a room, which is equivalent to the lock in the room, which, at first, is opened by default, and when a thread needs to execute the synchronized code, You need to determine if you can enter this room, that is, if the lock is open. If the lock is open, then the thread will go into the room, thus executing the code that is synchronized, by the way, the lock is locked, the other thread if also to run the synchronized code, it is necessary to determine whether to go in, but this time the lock is locked, that is, the other thread does not go in. That is, as long as the thread is executing the synchronized code, the other threads are no longer able to execute. When the thread executes the synchronized code, when it goes out of the room, it opens the lock, and at this point the other threads have access to the room to execute the code.

Prerequisites for synchronization:

1. Must be two and more than two threads

Just one thread does not need a lock, all code is it to execute

2. Must be multiple threads using the same lock

It means that multiple threads are in a room, and if each thread enters the corresponding room, what is the difference between a lock and an unlocked one?

Guarantee that there is only one thread in the room

Benefits: Addressing security issues

Disadvantage: The thread needs to judge the lock when executing the code, and consumes a certain amount of resources.



Java------Multithreading: to solve the security problem of multithreading---synchronized synchronous code block

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.