1. Why use synchronized, because in the case of multithreading, dirty data will be read.
Why is there read dirty data, his definition is: in the case of multi-threaded, the same object of the instance of concurrent access , if not synchronous processing, it is possible to read dirty data.
For example, 2 threads were started to access the object Mythreadtest T. Because I want to use this object in the thread, I use the constructor method to pass the parameters.
The final print out I are all 200, so that is problematic, how can we avoid this result, add synchronized to the test method above the keyword.
Synchronized concept: The keyword Synchronize acquisition lock is an object lock, not a lock on this method . The thread executes first, acquires the lock of the object that owns the method , and which thread holds the lock of the object to which the method belongs .
Other threads can only be in a wait state. But there is a premise: since locks are called object locks, it is bound to be related to objects, so multiple threads must access the same object .
2 methods add the Synchronized keyword, so access is synchronized, there is no problem, if the 1 to change to a common method. There may be a problem.
1 If a thread holds a lock on an object, thread B can call a method that is not decorated with synchronized, and wireless waits
2 If a thread holds the lock on the object, thread B also calls the synchronous method, then a release lock is required for B to enter,
Lock re-entry: When a thread obtains an object lock, it can again get the lock of the object once it is requested again.
The keyword synchronized has a lock-in feature. See an example:
Synchronized mechanism in Java Multi-threading