Use of the Java Multi-threaded keyword volatile

Source: Internet
Author: User

The role of the Java Multithreading Keyword volatile is to indicate that multiple threads share this variable.

If it is read-only can be used directly, when writing data should pay attention to synchronization problems.

Example:

 PackageCom.ming.thread.volatiletesttrhead1;/*** Volatile keyword use * volatile this keyword is used to keep variables modified by this keyword to be visible between multiple threads *@authorMingge **/ Public classVolatiletesttrheadextendsthread{volatile  Public Static intcount; //If you remove the Synchronized keyword, it will cause the data to be out of sync    synchronized Private Static voidAddcount () { for(inti=0;i<100;i++) {Count++; } System.out.println ("Count=" +count); }         Public voidrun () {addcount (); }}

 PackageCom.ming.thread.volatiletesttrhead1; Public classRun { Public Static voidMain (string[] args) {volatiletesttrhead[] Mythreadarr=Newvolatiletesttrhead[100];  for(inti=0;i<100;i++) {Mythreadarr[i]=NewVolatiletesttrhead (); }                 for(inti=0;i<100;i++) {Mythreadarr[i].start (); }            }}

Hey...

Use of the Java Multi-threaded keyword volatile

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.