Java class Lock and Object lock (instance lock) synchronization problem

Source: Internet
Author: User

It is well known that synchronized can be used to modify methods and blocks of code for classes or objects.

When a code block is decorated, synchronized (object) acts on the object, constraining only that object.

Synchronized (class) acts on a class, constraining all objects of the class.

When modifying a method, the synchronized modifies the static method for the class. Used for objects when modifying non-static methods.

Note Class and object locks are two different locks, and they do not have a synchronization relationship.

Because of the static variable, it can be called by the static method, or it can be called by a non-static method, and when both are synchronized decorated, there is a potential synchronization problem.

Therefore, multi-threading static variables as far as possible only static method calls, otherwise there will be synchronization confusion.

Class Test implements runnable{    public  static  int num = 0;    Public synchronized void Changenum () {        num++;        SYSTEM.OUT.PRINTLN (num);    }      Public synchronized static void Addnum () {        num++;        SYSTEM.OUT.PRINTLN (num);    }    @Override public    Void Run () {for        (int i = 0; i < i++) {            changenum ();            Addnum ();            try {                thread.sleep (5);            } catch (Interruptedexception IE) {}}} public    static void Main (string[] args) {         test test = new Test ();        thread T1 = new thread (test);        Thread t2 = new Thread (test);        T1.start ();        T2.start ();    }}

If you synchronize, the result should be 8000, but not.

Java class Lock and Object lock (instance lock) synchronization problem

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.