Thread synchronization Synchronized,class with Object

Source: Internet
Author: User

Synchronized (Class): Class synchronization, synchronization will synchronize the entire class

And

Synchronized (object): Synchronization of object, only for objects in which it is synchronized

As follows: synchronization of the synchronous code block in Class B, after contrast, can be understood

Synchronized (Mythread.class)

Cases:

A: Class Unsafesequence

public class Unsafesequence {
private static int value;

public int GetValue ()
{
Synchronized (Unsafesequence.class) {
return value++;
}
}

public int Getvaluea ()
{
Synchronized (this) {
return value++;
}
}
}

B: Class Mythread

public class MyThread implements Runnable {
Private unsafesequence unsafe;
private static int value;

@Override
public void Run () {
unsafe = new unsafesequence ();
for (int i = 0; i <; i++)
{
Synchronized (Mythread.class) {
System.out.println (Thread.CurrentThread (). GetName () + "----in:");
System.out.println (Thread.CurrentThread (). GetName () + "Thread run i =" + i + "; value =" + Unsafe.getvalue ());
System.out.println (Thread.CurrentThread (). GetName () + "----out:" + value++);
}
}
}

}

C: Main function

public class Testmain {
public static void Main (string[] args) {
MyThread target_1 = new MyThread ();
MyThread target_2 = new MyThread ();
Thread thread_1 = new Thread (target_1, "A");
Thread thread_2 = new Thread (target_2, "B");
Thread_1.start ();
Thread_2.start ();
}
}

The results are as follows:

B----in:
B thread Run i = 0;value = 0
B----out:0
B----in:
B thread Run i = 1;value = 1
B----out:1
B----in:
B thread Run i = 2;value = 2
B----Out:2

Remove the synchronization in B, or change to object, the result is as follows:

A----in:
B----in:
A thread Run i = 0;value = 0
B thread Run i = 0;value = 1
A----out:0
B----out:1
A----in:
B----in:
A thread Run i = 1;value = 2
B thread Run i = 1;value = 3
B----Out:3
B----in:
A----Out:2

Thread synchronization Synchronized,class with Object

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.