Java uses the keyword synchronized for thread synchronization with four sync blocks:
1. Example method
2. Static method
3. Synchronization blocks in the instance method
4. Synchronous block in static method
Instance method synchronization: Use the Synchronized keyword in the method declaration to synchronize on the object that owns the method
1 Public synchronized void Increase () {2 this. id++; 3 }
Static method synchronization: As with instance method synchronization, use the Synchronized keyword in the method declaration to synchronize on the class object that owns the method, while allowing only one thread to execute a static synchronization method in the same class
1 Public Static synchronized void Increase () {2 this. id++; 3 }
Synchronization blocks in instance methods: Do not use the Synchronized keyword in the method declaration, but use synchronized to enclose part of the code in the method to synchronize
1 Public void Increase () {2 synchronized (this) {3 this. id++; 4 }5 }
Synchronous blocks in static methods: Similar to static method synchronization, do not use the Synchronized keyword in the method declaration, use synchronized to surround part of the code in the method, synchronize
1 Public Static void Increase () {2 synchronized (this) {3 this. id++; 4 }5 }
Multiple threads: Thread synchronization code block