When multiple threads are accessing resources simultaneously, the synchronization mechanism allows only one thread to operate on the resource at the same time.
The synchronization mechanism can be implemented with synchronized.
When synchronized modifies a method, the method is called the synchronization method.
Locks are released when the Synchronized method executes or is an exception.
There will be classmates on the synchronized modification method, static method, the object when the specific things to lock not very clear, here will be detailed explanation.
- When synchronized modifies a method, the class instance is locked, and all the synchronized methods of that instance must be accessed after the current lock is released.
- When synchronized modifies a static method, the class object is locked, and the synchronized method of the other instance of the class must be accessed only after the current lock is released.
- When synchronized modifies an object, it locks the object, and other synchronized methods that use the object must be accessible only if the current lock is released.
When you do not use the synchronized adornment method
A total of three classes were used in the code design.
The example class is a public resource and is accessed by multiple threads.
In this case, two threads are accessed.
Class Example {public void exec () {for (int i = 0; i <; i++) { try {long time = (long) (Math.rand Om () * +); Thread.Sleep (time); } catch (Interruptedexception ex) { ex.printstacktrace (); } System.out.printf ("%s,hello[%d]\n", Thread.CurrentThread (). GetName (), i);}}}
The Mythread class is a thread class that is used to access example public resources.
Class MyThread extends Thread { private final Example Example; Public MyThread (Example Example) { this.example = Example; } @Override public Void Run () { example.exec (); }}
Testsynchronized is the main class that is used for the new thread and starts.
public class Testsynchronized {public static void Main (string[] args) { Example Example = new Example (); MyThread thread1 = new MyThread (example); MyThread thread2 = new MyThread (example); Thread1.start (); Thread2.start (); }}
Since the method of the example class is not using the synchronous method, two threads will access the method at the same time, and the printed values are unordered as follows:
When using the Synchronized decoration method
We need to revise the method of example this public resource.
Class Example {public synchronized void exec () {for (int i = 0; i <; i++) { try {long time = (lon g) (Math.random () * +); Thread.Sleep (time); } catch (Interruptedexception ex) { ex.printstacktrace (); } System.out.printf ("%s,hello[%d]\n", Thread.CurrentThread (). GetName (), i);}}}
For the Exec method plus the Synchronized keyword, the method can have only one thread access at a time.
Java High concurrency Programming Learning: Synchronized synchronous code block specific use method