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