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