In concurrent environments, you can consider the use of lock mechanisms when resolving shared resource conflict issues.
1. Lock of Object
All objects automatically contain a single lock.
The JVM is responsible for tracking the number of times an object is locked. If an object is unlocked, its count becomes 0. When a task (thread) locks an object for the first time, the count changes to 1. The count increments whenever this same task (thread) Gets a lock on this object.
Only the task (thread) that obtains the lock first can continue to acquire multiple locks on the object.
Every time a task leaves a synchronized method, the Count decrements, and when the count is 0, the lock is completely freed, and other tasks can use the resource at this time.
2.synchronized Sync block
2.1 Sync to a single object lock
When using synchronized blocks, if the synchronized blocks under the method are synchronized to a lock on an object, all tasks (threads) can only be mutually exclusive into these synchronized blocks.
Resource1.java demonstrated that three threads (including the main thread) attempted to enter a synchronized block of three different methods of a class, although these synchronized blocks are in different methods, but because they are synchronized to the same object (the current object synchronized (this)), So the approach to them is still mutually exclusive.
Resource1.java
package com.zj.lock;
import Java.util.concurrent.TimeUnit;
public class Resource1 {
public void F () {
//Other operations should is locked ...
System.out.println (Thread.CurrentThread (). GetName ()
+ ": not synchronized in F ()");
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println (Thread.CurrentThread (). GetName ()
+ ": Synchronized in F ()");
try {
TimeUnit.SECONDS.sleep (3);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}
public void G () {
//Other operations should is locked ...
System.out.println (Thread.CurrentThread (). GetName ()
+ ": not synchronized in G ()");
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println (Thread.CurrentThread (). GetName ()
+ ": Synchronized in G ()");
try {
TimeUnit.SECONDS.sleep (3);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}
public void H () {
//Other operations should is locked ...
System.out.println (Thread.CurrentThread (). GetName ()
+ ": not synchronized in H ()");
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println (Thread.CurrentThread (). GetName ()
+ ": Synchronized in H ()");
try {
TimeUnit.SECONDS.sleep (3);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}
public static void Main (string[] args) {
final Resource1 rs = new Resource1 ();
New Thread () {
public void Run () {
rs.f ();
}
}.start ();
New Thread () {
public void Run () {
RS.G ();
}
}.start ();
rs.h ();
}
}