1. Sync and lock
Each object in Java has a built-in lock that automatically obtains the lock on the object that executes the method when the program executes a non-static synchronized synchronization method.
An object has only one lock, and when one thread obtains a lock, other threads cannot enter the synchronized method or block of code on the object. Until the lock is released.
A thread can have multiple locks, for example, a synchronous method that calls another object in a synchronous method of an object
2. Synchronization of static methods
Synchronous static method, with the lock of the class object, namely Xx.class.
3. Thread-Safe classes
The methods in the class are synchronized, but it is still not necessarily safe to manipulate the class.
For example:
public class namelist{
Private List Namelist=collections.synchonizedlist (new LinkedList ());
public void Add (String name) {
Namelist.add (name);
}
Public stirng Removefirst () {
if (Namelist.size () >0) {
Return (String) namelist.remove (0);
}else{
return null;
}
}
}
Public classtest{
public static void Main (string[] args) {
Final NameList list=new namelist ();
Nl.add ("AAA");
classNamedropperextendsthread{
Public voidRun () {
String name = Nl.removefirst ();
SYSTEM.OUT.PRINTLN (name);
}
}
Thread T1 =NewNamedropper ();
Thread t2 =NewNamedropper ();
T1.start ();
T2.start ();
}
}
Although the collection object is secure, the program is still problematic, and the workaround is to synchronize on two methods synchronized
Thread synchronization is implemented in 4.java:
A. Define the resources that need to be accessed synchronously as private
B. Where to modify this resource, using the method or code block of the Synchronized keyword synchronization operation
5. Summary:
Thread synchronization is designed to protect against resource corruption when accessing the same resource in multiple threads
Thread synchronization methods are implemented by locks, each object has only one lock, one thread obtains an object lock, and other threads cannot access the object's synchronization methods
For the static synchronization method, the lock is for this class, lock the object when the class object, static and non-static methods of lock non-interference,
A thread that does not acquire a lock will block when multiple threads are waiting for an object lock
Deadlocks are caused by threads waiting for each other's locks, deadlocks occur, programs die.
Java Threads: Synchronization and locking of threads