Java multithreaded programming model 4--synchronized

Source: Internet
Author: User
Tags static class

Before Java1.5, synchronized should be the most common Java support Concurrency tool. So, how did synchronized do that, starting with java1.0, each object in Java has an internal lock. If the method of a class is decorated by the Synchronized keyword, the lock of the object will protect the entire method.

For example:

Public synchronized void Method () {

Method body

}

Equivalent to

public void Method () {

This.intrinsicLock.lock ();

try{

Method body;

}finally () {

This.intrinsicLock.unlock ();

}

}

From the code example above, you can see that the synchronized is easier to use. This also led to a large number of beginners in the encounter Java programming in the trap, that since synhronized can handle everything, then regardless of 3,721, as long as there is the possibility of concurrency, add synchronized keyword, this is clearly wrong. In Java objects, this Java object has only this internal lock, where one synchronized method acquires the lock and another synchronized method is blocked.

That

Class sync{

Public synchronized void MethodA () {};

Public synchronized void MethodB () {};

... ...

}

MethodA and MethodB in the initial is mutually exclusive, if MethodA and methodb into each other wait, it is very easy to deadlock. So if this happens, what should be done. The common way is to create a new meaningless object inside the method and then add a pot to the meaningless object.

Package zl.study.concurrency.synchronize; public class Sync {private int i; public void Plus () {Object dummy = new object (); synchronized (dummy) {i++;}} public V OID minus () {Object dummy = new Object (); synchronized (dummy) {i--;}}}

Also note that it is legal to declare a static class as a synchronized method. For example, if sync has a static synchronized method, the Bank.class object itself will be locked in the JVM when the method is invoked.

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.