| Refresh | Home EGTry.com

the same thread can grap the lock that was holded by the same thread


Reentrant.java

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

package egtry.thread;

///reentrant synchronization: a thread can re-acquire a lock that it already own

public class Reentrant extends Thread {

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

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


  

  static class Counter {
	private int counter=0;
	
  public synchronized int incGet() {
	  inc();
	  return get();
  }
  public synchronized int get() {
	  System.out.println("get() Enter: ("+Thread.currentThread().getId()+") value="+counter);
	  	sleep();
	  System.out.println("get()  Exit: ("+Thread.currentThread().getId()+") value="+counter);
	  System.out.println("\n");
	  return counter;
  }
  
  public synchronized int inc() {
	  System.out.println("inc() Enter: ("+Thread.currentThread().getId()+") value="+counter);
	  sleep();
	  	counter++;
	  sleep();
	  System.out.println("inc()  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

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


get() Enter: (8) value=1
get()  Exit: (8) value=1


inc() Enter: (11) value=1
inc()  Exit: (11) value=2


get() Enter: (11) value=2
get()  Exit: (11) value=2


inc() Enter: (17) value=2
inc()  Exit: (17) value=3


get() Enter: (17) value=3
get()  Exit: (17) value=3


inc() Enter: (9) value=3
inc()  Exit: (9) value=4


get() Enter: (9) value=4
get()  Exit: (9) value=4


inc() Enter: (15) value=4
inc()  Exit: (15) value=5


get() Enter: (15) value=5
get()  Exit: (15) value=5


inc() Enter: (14) value=5
inc()  Exit: (14) value=6


get() Enter: (14) value=6
get()  Exit: (14) value=6


inc() Enter: (13) value=6
inc()  Exit: (13) value=7


get() Enter: (13) value=7
get()  Exit: (13) value=7


inc() Enter: (16) value=7
inc()  Exit: (16) value=8


get() Enter: (16) value=8
get()  Exit: (16) value=8


inc() Enter: (12) value=8
inc()  Exit: (12) value=9


get() Enter: (12) value=9
get()  Exit: (12) value=9


inc() Enter: (10) value=9
inc()  Exit: (10) value=10


get() Enter: (10) value=10
get()  Exit: (10) value=10