Java synchronized (Class) depth parsing __java

Source: Internet
Author: User

Synchronizing test code:

Package com.zhiwei.thread;

    public class Threadsynchronizedclass {public static int sum = 0; public void Add () throws Interruptedexception {synchronized (threadsynchronizedclass.class) {Thread.
            Sleep (500);
            sum++;
        System.out.println (Thread.CurrentThread (). GetName () + ": add:" + sum);
            } public void Del () throws interruptedexception {synchronized (threadsynchronizedclass.class) {
            Thread.Sleep (500);
            sum--;
        System.out.println (Thread.CurrentThread (). GetName () + ":d el:" + sum); }/** static Synadd as a member of the class, all instances are shared, and synchronized ensures that each instance is accessed synchronously/public synchronized static void Synadd () thro
        WS Interruptedexception {thread.sleep (500);
        sum++;
    System.out.println (Thread.CurrentThread (). GetName () + ": synadd:" + sum);
        Public synchronized static void Syndel () throws Interruptedexception {Thread.Sleep (500);
  sum--;      System.out.println (Thread.CurrentThread (). GetName () + ": Syndel:" + sum); /** * If access to external static variables has the same effect as synchronization * @param name * @throws interruptedexception/public void show (String name) throws Interruptedexception {synchronized (threadsynchronizedclass.class) {Thread.slee
            P (500); for (int i = 0; i < name.length (); i++) {System.out.println (Thread.CurrentThread (). GetName () + ":" + N
            Ame.charat (i)); }} public static void Main (string[] args) {Threadsynchronizedclass ThreadSynchronizedClass1
        = new Threadsynchronizedclass ();

        Threadsynchronizedclass threadSynchronizedClass2 = new Threadsynchronizedclass (); for (int i = 0; i < i++) {new Thread (new Runnable () {@SuppressWarnings ("static-acces S ") @Override public void Run () {try {thread SynchRonizedclass1.synadd ();
                    catch (Interruptedexception e) {e.printstacktrace ();
            }}). Start ();
                New Thread (New Runnable () {@SuppressWarnings ("static-access") @Override
                    public void Run () {try {Threadsynchronizedclass2.syndel ();
                    catch (Interruptedexception e) {e.printstacktrace ();
            }}). Start ();
                        New Thread (New Runnable () {@Override public void run () {try {
                    Threadsynchronizedclass2.show ("ABCDEFGHIJKLMN");
                    catch (Interruptedexception e) {e.printstacktrace ();
            }}). Start ();

  New Thread (New Runnable () {              @Override public void Run () {try {THREADSYNCHR
                    Onizedclass1.show ("ABCDEFGHIJKLMN");
                    catch (Interruptedexception e) {e.printstacktrace ();
        }}). Start ();
 }

    }
}
Effect

Conclusion :

Static Synchronized method is equivalent to synchronized (class) internal access to statically member variables, because static-decorated object members are subordinate to the class itself and are stored in the JVM's methods area. All object instances refer to the same class object in the method area, so locking class can achieve the effect of synchronization

Explore: What's the effect if you set the sum to a non-static property?
Test code:

Package com.zhiwei.thread; /** * Lock byte code class: * 1.synchronized (Class) Sync code block has synchronization effect on accessing external static member variable, non-static member variable does not have synchronization effect * 2.static Synchronized method is equivalent to SYNCHR  Onized (Class) internal access static member variable * 3.synchronized (Class) synchronous code block access to local variables with synchronization effect * * Public class Threadsynchronizedclass {public

    int sum = 0; public void Add () throws Interruptedexception {synchronized (threadsynchronizedclass.class) {Thread.
            Sleep (500);
            sum++;
        System.out.println (Thread.CurrentThread (). GetName () + ": add:" + sum);
            } public void Del () throws interruptedexception {synchronized (threadsynchronizedclass.class) {
            Thread.Sleep (500);
            sum--;
        System.out.println (Thread.CurrentThread (). GetName () + ":d el:" + sum); } public static void Main (string[] args) {Threadsynchronizedclass threadSynchronizedClass1 = new THR
        Eadsynchronizedclass (); Threadsynchronizedclass threadSynchronizedClass2 = new ThReadsynchronizedclass ();
                        New Thread (New Runnable () {@Override public void run () {try {
                    while (true) Threadsynchronizedclass1.add ();
                    catch (Interruptedexception e) {e.printstacktrace ();
            }}). Start ();
                        New Thread (New Runnable () {@Override public void run () {try {
                    while (true) Threadsynchronizedclass2.del ();
                    catch (Interruptedexception e) {e.printstacktrace ();

    }}). Start ();
 }}
Effect:

Analysis:

From the console log, different object instances do not achieve the effect of synchronization, so you can draw a stage syschronized (class) only for static member properties can play a synchronous role

Depth Analysis: synchrozized (Class) Although the byte code of the class is locked, but because the sum is a non-static property, when the class is instantiated, sum is not saved in the method area, but is saved in the JVM heap, and sum is subordinate to the class instance. So when two objects access the synchronization method defined by the class does not achieve the effect of synchronization, the individual thinks that the JVM has some kind of checking mechanism, when using synchronized (class) to synchronize, check whether there is a shared resource, if there is no shared resources so synchronous failure, The static decorated sum is subordinate to the class itself, so that all class instances are shared so that the effect of synchronization can be achieved, and not the static sum is subordinate to the class instance itself, not the shared resource, and therefore does not reach the synchronization effect

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.