tags:

views:

77

answers:

2

what is synchronization of thread in java? give any example on it in detail

+4  A: 

Have a look at the java tutorial about synchronization.

tangens
Also please read Concurrency in pratice by Doug Lea.
Suresh S
+1  A: 

In multi-threaded programs there are often sections of the program that need to be run atomically (as if it were a single operation). These are generally referred to as critical regions and are protected using mutual exclusion (mutex) paradigms. The synchronized keyword in Java is one such way of providing mutual exclusion.

Consider the code:

synchronized(lockObject) {
  //critical code
}

In the above code, only one thread may enter that synchronized block at a time so long as the object reference by the variable lockObject is never changed. This ensures that the code executed within the synchronized block is only ever executed by a single thread.

Common examples of where locking is needed would be when iterating over a collection. Few Java Collection implementations offer thread safe iteration. A basic way of creating thread safe iteration would be to protect every access to the collection with a synchronized block on that collection.

For example:

synchronized(myCollection) {
  myCollection.add(item);
}

synchronized(myCollection) {
  myCollection.remove(item);
}

synchronized(myCollection) {
  for(Object item:myCollection){
     System.out.println(item);
  }
}
Tim Bender