1. Shared, variable.
Stealing a lazy, here is the "Java Concurrent Programming Combat" section:
When I first saw this, I was a little dizzy.
The state of the object: the member variable, the static variable, and the other dependent object's fields are the state of the object.
If an object is stateless (there are no member variables and static variables, and no other dependent fields), then this object is absolutely thread-safe.
Sharing: means that the state of an object can be accessed concurrently by multiple threads. Variable sharing explains that your variables can be accessed directly or indirectly through methods (for example, the GetXXX () method).
Mutable: means that the value of a variable can change over its life cycle.
Whether an object requires thread safety depends on whether it is accessed by multiple threads.
If multiple threads are accessing the same mutable state variable without proper synchronization, the program will have an error.
2. Built-in lock
Java provides a built-in locking mechanism to support atomicity: synchronous blocks of code (Synchronized block). A synchronous code block consists of two parts: an object reference as a lock, and a block of code that is protected as a lock. The object reference to the lock is the object of the method invocation (which object is called, which object is used as the lock), and the block of code is the entire method body, in the synchronized decorated method of the keyword. The static synchronized method takes a class object as a lock.
synchronized // to lock an object with obj // synchronizing code blocks }
Each Java can be used as a lock that implements synchronization, which is called a built-in lock or a monitoring lock. The thread automatically obtains the lock before it enters the synchronization code block and automatically releases the lock when exiting the synchronization code block, whether it exits gracefully or throws an exception. The only way to get a built-in lock is to enter this lock-protected synchronous code block or method.
Each built-in lock is a mutex, which means that only one thread can hold the lock at most.
synchronized (c) {.... . A synchronous code block }// when a thread x goes here, if there is already a thread y entering a synchronous code block (or b synchronous code block) to get the built-in lock of the C lock object, then this thread x must wait or block Synchronized(c) {.... A synchronous code block }
Re-entry: If a thread attempts to obtain a lock that is already held by itself, the request succeeds.
class A { public synchronized void hehe () {System.out.println (" A " public class B extends a{ public synchronized void hehe () { System.out.println ( "B" ); super . hehe (); //
Second, synchronized