| Refresh | Home EGTry.com

a simple example to demonstrate the issue when multiple threads write using unsynchronized method


UnSynchronizedMethod.java

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

package egtry.thread;

///multiple threads read/write the shared object and return unexpected result 
public class UnSynchronizedMethod extends Thread {

  private Counter counter;
  
  public static void main(String[] args) {
	Counter counter=new Counter();
	for(int i=0; i<10; i++) {
		UnSynchronizedMethod t=new UnSynchronizedMethod(counter);
		t.start();
	}
  }
  
  public UnSynchronizedMethod(Counter counter) {
	  this.counter=counter;
  }

  @Override
  public void run() {
	  int id=counter.incGet();
  }
  


  
  static class Counter {
  private int counter=0;
  public  int incGet() {
	  System.out.println("synchronized Enter: ("+Thread.currentThread().getId()+") value="+counter);
	  sleep();
	  counter++;
	  sleep();
	  System.out.println("synchronized  Exit: ("+Thread.currentThread().getId()+") value="+counter);
	  System.out.println("\n");
	  return counter;
  }
  

  
  public void sleep() {
	  int millis=(int)Math.random()*1000;
	  try {
		  Thread.sleep(millis);
	  } catch (Exception e) {
		  
	  }
  }
  }
}



Output

synchronized Enter: (8) value=0
synchronized  Exit: (8) value=1


synchronized Enter: (9) value=1
synchronized Enter: (10) value=1
synchronized Enter: (11) value=1
synchronized Enter: (12) value=4
synchronized Enter: (13) value=4
synchronized  Exit: (10) value=4


synchronized  Exit: (9) value=5


synchronized Enter: (14) value=5
synchronized Enter: (16) value=6
synchronized  Exit: (11) value=6
synchronized  Exit: (13) value=7




synchronized  Exit: (12) value=6


synchronized Enter: (15) value=7
synchronized  Exit: (16) value=8


synchronized  Exit: (14) value=8
synchronized  Exit: (15) value=9


synchronized Enter: (17) value=8


synchronized  Exit: (17) value=10