You have written:
synchronized(this) {
But
this
in all thread points to a different instance of your
ThreadEX
class
You can do one of the following:
1. Write in such way:
synchronized(ThreadEx.class) {
2. Use
ConcurrentHashTable
class.
Also, you re-initialize
table
in each thread. You should definitely fix this.
I have slightly changed your version:
public class ThreadEX implements Runnable {
private static Hashtable<Integer, String> table = new Hashtable<Integer,String>();
private boolean thCheck = false;
public ThreadEX() {
}
@Override
public void run() {
synchronized(ThreadEX.class) {
table.put(this.hashCode(), "tmp");
System.out.println(this.hashCode() + " added, size : " + table.size());
}
}
}
Good luck!