Usage of synchronized in Java

Source: Internet
Author: User

1, the scope of the SYNCHRONIZED keyword has two kinds:

1 is an object instance in which synchronized Amethod () {} can prevent multiple threads from simultaneously accessing the object's Synchronized method (if an object has multiple synchronized methods, As long as one thread accesses one of the synchronized methods, no other thread can access any of the synchronized methods in the object at the same time. At this point, the synchronized method of different object instances is not interfered. That is, other threads can still access the Synchronized method in another object instance of the same class at the same time;

2 is the scope of a class, synchronized static astaticmethod{} prevents multiple threads from accessing the synchronized static method in this class at the same time. It can work on all object instances of a class.

2, in addition to the method before using the Synchronized keyword, the synchronized keyword can also be used in a method of a block, indicating that only the resources of the block mutex access. The usage is: synchronized (this) {/* block/}, its scope is the current object;

3, the Synchronized keyword is not inherited, that is, the base class method synchronized F () {} is not automatically synchronized F () {} in the inheriting class, but instead becomes F () {}. An inheriting class requires that you explicitly specify one of its methods as the Synchronized method;

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.