How to master Synchronized
This article mainly explains "how to master Synchronized". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's take you to learn "How to master Synchronized"!
use
Synchronized keyword is one of the common means of thread synchronization in Java concurrent programming, and its role has three functions:
Mutual exclusion: ensure that threads mutually exclusive access synchronization generation, lock automatic release, multiple threads operating on the same code block or function must queue to obtain locks,
Visibility: Ensure that the modification of shared variables can be visible in time, and the thread that obtains the lock will refresh the data to the shared memory area after the operation is completed [1]
Orderability: Effective solution to reordering problems
There are three ways to synchronize:
modification instance method
modifying static methods
decorated code block
1. modification instance method
The synchronized keyword is used in front of the method to lock the method. In fact, the default lock is this object.
public class Thread1 implements Runnable{ //Shared resources (critical resources) static int i=0; //If there is no synchronized keyword, the output is less than 20000 public synchronized void increase(){ i++; } public void run() { for(int j=0;j