It's strange to write this kind of article here, first as a note.
Java has the following methods to handle concurrent access problems with blocks of code:
One is the keyword synchronized
The second is locking (lock object, condition object)
Java provides an internal lock for each object, and after the keyword synchronized is added to the definition of the method, the lock of the object will protect the entire method. In other words, the following two types of notation are equivalent:
Public synchronized void Method ()
{
......
}
public void Method ()
{
This.intrinsickLock.lock ();
Try
{
......
}
Finally
{
This.intrinsickLock.unlock;
}
}
Java Core is not recommended for either of these methods!
Key Words synchronized Interpretation:
The synchronized implementation principle is that Java has a lock built into each object. For a common method of a class, synchronized locks the method of each new object, for example, the following code:
public class test{
public void synchronized TestMethod ()
{
.......
}
}
Test obj1 = new test ();
Test obj2 = new test ();
If Thread-1 access is obj2, then two threads will not block because this is two different objects.
If Thread-1 accesses obj1,thread-2 access is also obj1, then Thread-2 will block because two threads are accessing the same object, but Thread-1 acquires the lock first, so Thread-2 must wait for Thread-1 to release the lock Before you can access it.
For a static method, synchronized becomes a class lock, and for the scenario described above, the Thread-2 is blocked in both cases because the static method is shared by all objects of the class.
Synchronized can lock blocks of code in addition to locking the entire method.
One way to do this is:
public void Method ()
{
Synchronized (This)
{
....
}
.....
}
Another way to do this is:
Object obj = new Object ();
public void Method ()
{
Synchronized (obj)
{
....
}
.....
}
The second way is more flexible. When using synchronized, it is necessary to be careful about the excessive use of synchronized to protect, causing performance problems.
How Java handles multi-threaded data synchronization issues