| Refresh | Home EGTry.com

synchronize a block of statement


SynchronizedStatement.java

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

package egtry.thread;

///multiple threads read/write shared object through synchronized statments
public class SynchronizedStatement extends Thread {

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

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


  

  static class Counter {
	private int counter=0;
	private Object lock=new Object();
	
  public int incGet() {
	  synchronized (lock) {
		  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: (9) value=0
synchronized  Exit: (9) value=1


synchronized Enter: (16) value=1
synchronized  Exit: (16) value=2


synchronized Enter: (14) value=2
synchronized  Exit: (14) value=3


synchronized Enter: (17) value=3
synchronized  Exit: (17) value=4


synchronized Enter: (12) value=4
synchronized  Exit: (12) value=5


synchronized Enter: (15) value=5
synchronized  Exit: (15) value=6


synchronized Enter: (10) value=6
synchronized  Exit: (10) value=7


synchronized Enter: (13) value=7
synchronized  Exit: (13) value=8


synchronized Enter: (8) value=8
synchronized  Exit: (8) value=9


synchronized Enter: (11) value=9
synchronized  Exit: (11) value=10