Reputation: 497
enter code hereSuppose I have two threads Thread1 and Thread2 and below hashmap with null values. Now I want to print the Key of HashMap with respective thread which is executing print statement , without printing it again
Input Hashmap:
"Hello" null
"Customer" null
"Value" null
"Bye" null
Output:
"Bye" : Printed by Thread1"
"Hello" :"Printed by Thread2"
"Value" :"Printed by Thread2"
"Customer" : "Printed by Thread1"
So Far I am not able to print with below code.
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test2 implements Runnable {
volatile static HashMap<String, String> map;
static Object mutex = new Object();
static volatile int i = 1;
public static void main(String[] args) throws InterruptedException {
map = new HashMap();
map.put("Public", null);
map.put("Sort", null);
map.put("Message", null);
map.put("Customer", null);
map.put("Bank", null);
// ConcurrentHashMap chm= new ConcurrentHashMap(map);
Collections.synchronizedMap(map);
Thread t1 = new Thread(new Test2());
Thread t2 = new Thread(new Test2());
t1.start();
t2.start();
}
@Override
public void run() {
synchronized (mutex) {
for (Map.Entry entry : map.entrySet()) {
if (entry.getValue() == null) {
System.out.println(entry.getKey() + "\" : \"Printed by " + Thread.currentThread().getName() + '\"');
map.put((String) entry.getKey(), Thread.currentThread().getName());
if (Thread.currentThread().getName().contains("0")&&i==1) {
try {
mutex.notifyAll();
mutex.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (Thread.currentThread().getName().contains("1")&&i<=1) {
try {
mutex.notifyAll();
i++;
mutex.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
mutex.notifyAll();
}
}
}
Upvotes: 0
Views: 670
Reputation: 11308
Just pass each key as a task to an ExecutorService with 2 threads :
ExecutorService executorService = Executors.newFixedThreadPool(2);
map.keySet().forEach(key -> executorService
.execute(() -> System.out.println('\"' + key + "\" : \"Printed by " + Thread.currentThread().getName() + '\"')));
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
Upvotes: 3