Java has the following methods to handle concurrent access to code blocks:
First, the keyword synchronized
Second, lock (Lock Object, condition object)
Java provides an internal lock for each object. After the keyword synchronized is added to the method definition, the object lock will protect the entire method. That is to say, the following two statements are equivalent:
Public synchronized void method ()
{
......
}
Public void method ()
{
This. intrinsickLock. lock ();
Try
{
......
}
Finally
{
This. intrinsickLock. unlock;
}
}
The above two methods are not recommended in Java Core!
Key words synchronized explanation:
The principle of synchronized implementation is that Java has a built-in lock for every object. For a common method of a class, synchronized locks every new object method, for example, for the following code:
Public class Test {
Public void synchronized testMethod ()
{
.......
}
}
Test obj1 = new Test ();
Test obj2 = new Test ();
If Thread-1 accesses obj1 and Thread-2 accesses obj2, neither Thread will be blocked because these are two different objects.
If Thread-1 accesses obj1 and Thread-2 also accesses obj1, Thread-2 will be blocked because the two threads access the same object, but Thread-1 gets the lock first, so Thread-2 must wait until Thread-1 releases the lock before access.
For a static method, synchronized becomes a class lock. In both cases, Thread-2 will be blocked, because static methods share all objects of the class.
In addition to locking the entire method, synchronized also locks the code block.
One method is:
Public void method ()
{
Synchronized (this)
{
....
}
.....
}
Another method is:
Object obj = new Object ();
Public void method ()
{
Synchronized (obj)
{
....
}
.....
}
The second method is more flexible. When synchronized is used, you need to be careful when using synchronized for protection, resulting in performance problems.