Java multi-thread visibility and atomicity--synchronized VS volatile

Source: Internet
Author: User






















Examples of programs:

Code:

Package Com.synch;public class Synchronizeddemo {//Shared variable private Boolean ready = false;    private int result = 0;       private int number = 1;          Write operation public synchronized void write () {ready = true;                           Number = 2;     }//read operation public synchronized void read () {if (ready) {result = Number*3;    } System.out.println ("The value of result is:" + result); }//Internal thread class private class Readwritethread extends thread {///depending on the flag parameter passed in the constructor method, determines whether the thread performs a read or write operation Private Boolean FLA    G    Public Readwritethread (Boolean flag) {This.flag = flag; } @Override public void Run () {i        The f (flag) {///constructor method passes in true, performing write writes ();        }else{//construct method to pass in false, perform read operation reading ();    }}} public static void Main (string[] args) {Synchronizeddemo Syndemo = new Synchronizeddemo (); Initiates a thread to perform a write operation Syndemo. New Readwritethread (True). Start ();//try {//thread.sleep (+),//} catch (Interruptedexception e) {////TODO auto-generated catch Block//e.pri    Ntstacktrace ();///start thread to perform read operation Syndemo.new Readwritethread (FALSE). Start (); }}















code example:

package com.synch;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class Volatiledemo {private lock lock = new Reentrantlock ();p rivate int Number = 0;public int GetNumber () {return this.number;} public void Increase () {try {thread.sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.print StackTrace ();} Lock.lock (); try {this.number++;} finally {Lock.unlock ();}}  /** * @param args */public static void main (string[] args) {//TODO auto-generated method stubfinal Volatiledemo Voldemo = New Volatiledemo (); for (int i = 0; i < i++) {new Thread (new Runnable () {@Overridepublic void run () {Voldemo.incre ASE ();}}). Start ();} If there are sub-threads running, the main thread will let the CPU resources,//until all the sub-threads are running, and the main thread continues to execute while (Thread.activecount () > 1) {//Let all child threads execute, then execute <   Pre name= "code" class= "Java" >//system.out.println ("number:" + voldemo.getnumber ()); Statement. Because the main thread counts one. When the active thread is 1 o'clock, that is, all of the child threads have finished executing. This///exits the while loop to execute the output statement. 
Thread.yield ();} System.out.println ("Number:" + voldemo.getnumber ());}}
























































































Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java multi-thread visibility and atomicity--synchronized VS volatile

Related Article

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.