Here is my main class that initializes and starts 5 different Threads:
public class Server implements Runnable { Server1 server1; Thread server1Thread; public Server() {} @Override public void run() { server1 = new Server1(); server1Thread = new Thread(server1); server1Thread.start(); } public static void main(String[] args) { for (int i = 0; i < 5; i++) { Server s = new Server(); s.run(); } } } Here is my Server1 Runnable:
import java.util.concurrent.ConcurrentHashMap; public class Server1 implements Runnable { private ConcurrentHashMap<Integer, Integer> storage= new ConcurrentHashMap<>(); public Server1() {} @Override public void run() { synchronized (this){ for (int i = 0; i < 10; i++) { storage.put(i, (int)(Math.random()*100)); } for (int i : storage.keySet()) { System.out.print("(" + i + "," + storage.get(i) + ") "); } System.out.println(); } } } It puts in ConcurrentHashMap storage keys from 0 to 9 and assigns them a random value between 0 and 100. After that it prints it and prints new line at the end. I have user synchronized block to make sure the thread itself access keys correctly but it prints something like this:
(0,8) (0,87) (1,60) (1,14) (2,20) (2,70) (3,5) (0,74) (0,42) (1,22) (4,96) (0,85) (1,97) (2,75) (3,68) (4,3) (5,49) (6,3) (7,9) (8,47) (9,52) (3,2) (5,74) (2,86) (1,48) (3,5) (6,0) (4,0) (7,86) (4,22) (8,20) (2,17) (9,87) (5,96) (5,15) (6,15) (6,92) (7,48) (8,93) (9,67) (3,87) (7,43) (4,34) (5,48) (8,91) (9,64) (6,84) (7,75) (8,47) (9,87) which obviously means that some thread prints more that 10 keys that I assigned to it. How do I make every thread print exactly 10 keys and values that it is assigned to them and ensure concurrency here?
I am not sure how to test it.
synchronized(System.out)instead of usingsynchronized(this). If you do that, your threads will at least share the same lock.