The Java language keyword that, when used to decorate a method or a block of code, guarantees that at most one thread executes the code at the same time.
1. When the method declaration is used, it is placed before the scope operator (public, etc.), before the return type declaration (void, etc.). at this point, the thread obtains a member lock, that is, only one thread can enter the method at a time, and the other thread wants to call the method at this time, only queued, the current thread ( Is the thread inside the synchronized METHOD) after the method is executed, other threads can enter.
For example:
Public synchronized void Synmethod () {
Method body
}
2. for a block of code, synchronized followed by parentheses, in parentheses is a variable so that only one thread at a time enters that block of Code. at this point, the thread obtains a member Lock. for example:
public int Synmethod (int A1) {
Synchronized (a1) {
Only one thread can enter at a time
}
}
3.synchronized After the parenthesis is an object, at this point, the thread obtains an object lock. for example:
public class MyThread implements Runnable {
public static void main (String Args[]) {
MyThread mt = new MyThread ();
Thread T1 = new Thread (mt, "t1");
Thread t2 = new Thread (mt, "t2");
Thread t3 = new Thread (mt, "t3");
thread t4 = new thread (mt, "t4");
Thread t5 = new Thread (mt, "t5");
Thread t6 = new Thread (mt, "t6");
T1.start ();
T2.start ();
T3.start ();
T4.start ();
T5.start ();
T6.start ();
}
public void Run () {
synchronized (this) {
System.out.println (thread.currentthread (). GetName ());
}
}
}
For 3, If a thread enters, it gets the current object lock, and no action on all objects of that class can be made by another thread. using locks at the object level is often a coarser approach. Why would you lock the entire object and not allow other threads to use other synchronization methods in the object briefly to access the shared resources? If an object has more than one resource, you do not need to lock all the threads out just so that one thread can use a subset of the Resources. Because each object has a lock, you can use the virtual object to lock it as follows:
Class Finegrainlock {
Mymemberclass x, y;
Object Xlock = new Object (), ylock = new Object ();
public void Foo () {
Synchronized (xlock) {
Access x here
}
Do something here-but don ' t use shared resources
Synchronized (ylock) {
Access Y here
}
}
public void Bar () {
Synchronized (this) {
Access both X and Y here
}
Do something here-but don ' t use shared resources
}
}
4.synchronized followed by a class in parentheses, at which point the thread obtains an object lock. for Example:
Class arraywithlockorder{
private static Long num_locks = 0;
Private Long lock_order;
Private int[] arr;
Public Arraywithlockorder (int[] A)
{
arr = a;
Synchronized (arraywithlockorder.class) {//-----here
num_locks++; Number of Locks Plus 1.
Lock_order = num_locks; Sets a unique lock_order for this object instance.
}
}
Public long Lockorder ()
{
Return lock_order;
}
Public int[] Array ()
{
Return arr;
}
}
Class SomeClass implements Runnable
{
public int Sumarrays (arraywithlockorder a1,
Arraywithlockorder A2)
{
int value = 0;
Arraywithlockorder first = a1; Preserves the array reference of one
Arraywithlockorder last = a2; Local Copy.
int size = A1.array (). length;
if (size = = A2.array (). Length)
{
If (a1.lockorder () > A2.lockorder ())//determine and set the lock of the object
{//order.
First = a2;
Last = a1;
}
Synchronized (first) {//lock The object in the correct order.
Synchronized (last) {
int[] arr1 = A1.array ();
int[] arr2 = A2.array ();
For (int i=0; i<size; I++)
Value + = arr1[i] + arr2[i];
}
}
}
Return value;
}
public void Run () {
//
}
}
For 4, if a thread enters, then all the operations of the thread in that class cannot be done, including static variables and static methods, and in fact, for the synchronization of blocks of code that contain static and static variables, we usually lock with 4来.
Ps:synchronized Usage Summary
Synchronized uses different places to affect the code:
1. Synchronized keyword Modification method
Suppose that P1, P2 is a different object of the same class, and this class defines synchronous blocks or synchronous methods for the following situations, P1, P2 can call Them.
Public synchronized void method () {
//
}
This is the synchronization method, when the synchronized lock is called to call this synchronization method Object. That is, when an object P1 the synchronization method in a different thread, they form mutual exclusion and achieve Synchronization. At the same time, if there are multiple synchronization methods in the object, when a thread is executed with one of the synchronized methods in the object, the other synchronization methods in that object do not allow other threads to Execute. however, another object generated by the class that this object belongs to P2 is able to invoke this method of adding the Synchronized keyword arbitrarily.
The example code above is equivalent to the following code:
public void method () {
Synchronized (this)
{
//..
}
}
This is a P1 object lock, which got the P1 object lock thread, to be able to call P1 synchronization method, and for P2, P1 this lock and he is irrelevant, the program may be in this situation to get rid of synchronization mechanism control, resulting in data confusion.
2. Synchronization block, The sample code is as Follows:
public void method () {
Synchronized (this)
{
//..
}
}
At this point, the lock is the so object, each object corresponding to a unique lock, so which thread to get this object lock who will be able to run the code he Controls. When there is a definite object as a lock, it is possible to write the program like this, but when there is no explicit object as a lock, just to allow a piece of code to synchronize, you can create a special instance variable (he has to be an Object) to act as a lock:
Private byte[] lock = new byte[0];
public void method () {
Synchronized (lock)
{
//
}
}
Note: a 0-length byte array object will be more economical to create than any Object-view compiled bytecode: generates a 0-length byte[] object with only 3 opcode, and Object lock = new Object () requires 7 lines of Opcode.
3. The synchronized action is applied to the static function, and the sample code is as Follows:
Class Foo
{
Public synchronized static void Method1 ()
{
//.
}
public void Method2 ()
{
Synchronized (foo.class)
//
}
}
Both of these synchronous methods call the class lock (class) of the class to which the object of this method belongs, not a specific object produced by this class.
Can infer: if a class defines a synchronized static function a, also defines a synchronized instance function b, then this class of the same object obj in a multi-threaded access to A and B two methods, will not constitute synchronization, Because their locks are not the Same. The lock of the A method is the class that obj belongs to, and the lock of B is the object to which obj belongs.
An explanation of synchronized usage in Java