Change code as
======================================
public class ThreadUnsafe
{
private static int commonCounter=0;
Synchronized public int getCount()
{return commonCounter;}
Synchronized public void addCount(int val) { commonCounter+=val;}
Synchronized public void subtractCount(int val)
{ commonCounter-=val; }
}
===============================================
This make sure that if u share a object of class among more than 1 thread at a time only one operation can be performed by any thread. e.g if thread 1 is subtracting at the same time other thread cannot perform any of above listed function.
b'coz
"At a time only one thread can access synchronized method(s) of an object"
By making all function above ur assure that all operation are atomic and treated as a
Unit.
hope it will help to some extent
Any Correction from Movers and Shakers of Javaranch
