Java-Preliminary Understanding-The 13th chapter-the premise of synchronization

Source: Internet
Author: User

One.

In future development, see a phenomenon: see the data error is caused by thread safety problems, followed by the synchronization measures, did not expect security problems still exist.

This is a painful situation because there is no solution at this time.

See the problem, think that synchronization can solve the problem, did not expect to solve. (Is it a matter of security that the correct use of synchronization can be resolved?) )

How is this problem caused? Here we have to introduce the premise of synchronization, that is, you can use synchronization to solve what problems.

Synchronization is due to the existence of multiple threads (alternating between multiple threads, resulting in a security risk) and, if a single thread, does not require synchronization at all.

Therefore, you must first ensure that there are multiple threads. Then make sure that multiple threads are using the same lock,

On one thread, no object locks are required. Synchronization within a thread, synchronization is not required.

Now modify the program so that multiple threads correspond to different object locks.

The DOS results show that there are multiple threads in the synchronization and there is an error in the data. Since each thread is turned on, it has its own run method, and each run method has its own

The local obj object means that each thread has its own lock, and once it has its own lock, it is no longer synchronized. It also means that there is only one thread running in a synchronous code block.

Why not put it outside of run, obj is a member variable, and in the object ticket T, obj is the same as NUM and is a member. There are two members in the object, one is num, the other is Obj,obj is the only one in memory, that is, the equivalent of four in the stack memory, (four threads in the stack, four run, there is naturally four obj)

Java-Preliminary Understanding-The 13th chapter-the premise of synchronization

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.