# # Java multithreading 02 (thread synchronization)

Source: Internet
Author: User

* 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 ...}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.