Click here to Skip to main content
15,889,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
public class Test {

	public static void main(String[] args) {

		for(int i=0; i<5; i++) {
			ThreadEX ex = new ThreadEX();
			new Thread(ex).start();
		}
		
	}

}

class ThreadEX implements Runnable {

	private static Hashtable<Integer, String> table;
	private boolean thCheck = false;
	
	public ThreadEX() {
		table = new Hashtable<Integer,String>();
	}
	
	public void run() {
		synchronized(this) {
			table.put(this.hashCode(), "tmp");		
			System.out.println(this.hashCode() + " added, size : " + table.size());
		}
	}
}


Hello, everyone.
I like to ask about multi-thread synchronization in Java.
There is a code above, which I used as an example.
I excepted it would make a result like this:

6413875 added, size : 1
5442986 added, size : 2
28737396 added, size : 3
827574 added, size : 4
24355087 added, size : 5

(hash code doesn't matter).

However, it doesn't at all. I think I have a problem with synchronizing hashtable, but I don't know what the wrong is for now.

Could you anyone give me any advice or correction of my synchronization code, to make a result like what I excepted?

Thank you!
Posted

1 solution

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:

Java
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!
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900