* The so-called synchronization mechanism means that two threads operate on an object at the same time, and the uniformity and integrity of the object data should be maintained.
* JAVA supports two synchronization modes: synchronous method and synchronous method.CodeBlock.
1. Synchronization Method
The synchronous method marks the methods used to access this resource as synchronized, so that other threads that call this method will be blocked before the threads that need to call this method are executed.
Synchronized void sum (){...}
Synchronized void max (){...}
* Example of creating two threads
Import java. util. Logging. level;
Import java. util. Logging. Logger;
Public class syncthread extends thread {
Private char cha;
Public syncthread (char CHA ){
This. CHA = CHA;
}
Public void run (){
Printclass. printch (CHA );
System. Out. println ();
}
Public static void main (string [] ARGs ){
Syncthread T1 = new syncthread ('A ');
Syncthread t2 = new syncthread ('B ');
T1.start ();
T2.start ();
}
}
Class printclass {
Public static void printch (char CHA ){
For (INT I = 0; I <5; I ++ ){
Try {
Thread. Sleep (1000 );
} Catch (interruptedexception ex ){
Logger. getlogger (printclass. Class. getname (). Log (level. Severe, null, ex );
}
System. Out. Print (CHA );
}
}
}
* Synchronization Block
Synchronization settings in Java are not only applied to synchronization methods, but also can be setProgramIs the synchronization area.
Syntax format:
Synchronized (someobject ){... Code ...}