| Refresh | Home EGTry.com

synchronize two instance methods


SynchronizedMethod2.java

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

package egtry.thread;

///two synchronized method1 and method2, while a thread is executing the method1, other threads can not executing the method2

public class SynchronizedMethod2 extends Thread {

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

  @Override
  public void run() {
	  int id=counter.get();
	  counter.sleep();
	  counter.inc();
  }
  


  

  static class Counter {
	private int counter=0;
  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

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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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