| Refresh | Home EGTry.com

declare a variable volatile to provide an immediate available memory model


VolatileLong.java

/*
 * Copyright@ 2011 www.egtry.com
 */

package egtry.thread;

///volatile long or double variables are reads/writes atomic
public class VolatileLong extends Thread {

	private static long value=0; //need to be volatile
	

  
  public static void main(String[] args) {
	int n=100;
	VolatileLong[] list=new VolatileLong[n];
	//create threads
	for(int i=0; i<n; i++) {
		VolatileLong t=new VolatileLong();
		list[i]=t;
	}
	
	//start threads
	for(int i=0; i<n; i++) {
		VolatileLong t=list[i];
		t.start();
	}
	
	//let all theads finish
	for(int i=0; i<n; i++) {
		VolatileLong t=list[i];
		try {
			t.join();
		} catch (InterruptedException e) {
			System.out.println("InterruptedException ");
		}
	}
	
	
	System.out.println("the final value: "+VolatileLong.value); //there is a possible that more than 1 instances are created.
  }
  

  


  @Override
  public void run() {
	  if (value==0) {
		  synchronized(VolatileLong.class) {
			  if (value==0) {
				  value++;
			  }
		  }
	  }

  }
  

}

  


Output

the final value: 1