Synchronized mechanism in Java Multi-threading

Source: Internet
Author: User

1. Why use synchronized, because in the case of multithreading, dirty data will be read.

Why is there read dirty data, his definition is: in the case of multi-threaded, the same object of the instance of concurrent access , if not synchronous processing, it is possible to read dirty data.

For example, 2 threads were started to access the object Mythreadtest T. Because I want to use this object in the thread, I use the constructor method to pass the parameters.

The final print out I are all 200, so that is problematic, how can we avoid this result, add synchronized to the test method above the keyword.

Synchronized concept: The keyword Synchronize acquisition lock is an object lock, not a lock on this method . The thread executes first, acquires the lock of the object that owns the method , and which thread holds the lock of the object to which the method belongs .

Other threads can only be in a wait state. But there is a premise: since locks are called object locks, it is bound to be related to objects, so multiple threads must access the same object .

2 methods add the Synchronized keyword, so access is synchronized, there is no problem, if the 1 to change to a common method. There may be a problem.

1 If a thread holds a lock on an object, thread B can call a method that is not decorated with synchronized, and wireless waits

2 If a thread holds the lock on the object, thread B also calls the synchronous method, then a release lock is required for B to enter,

Lock re-entry: When a thread obtains an object lock, it can again get the lock of the object once it is requested again.

The keyword synchronized has a lock-in feature. See an example:

Synchronized mechanism in Java Multi-threading

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.