Reputation: 159
I am searching for a simple Java Runnable example where 3 individual threads individually add a item to a hash table available to all threads and display on join of thread's completion.
Simple example:
Hashtable
Thread 1: Add to Hashtable Key1 Keyvalue1
Thread 2: Add to Hashtable Key2 Keyvalue2
Thread 3: Add to Hashtable Key3 Keyvalue3
on join print hashtable
Any help would be much appreciated,
Thank you
Upvotes: 1
Views: 694
Reputation: 1190
So what you want is a single HashTable which is edited by multiple Threads? There shall be 3 Threads and everyone shall put a diffent key and a different value into the Table and after every put the active thread shall print out all keys and values in pairs? Am i right? Because if, this might be something:
import java.util.Hashtable;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
public class Threadexample {
// Hashtable and Keylist
private Hashtable<String, Integer> table;
private CopyOnWriteArrayList<String> keys;
// Konstruktor
public Threadexample() {
table = new Hashtable<String, Integer>();
keys = new CopyOnWriteArrayList<String>();
}
// Adds an Item to the Table and prints the table
public synchronized void addItem(String key, int value, String threadname) {
// Adding
table.put(key, value);
if (!isAlreadyAdded(key)) {
keys.add(key);
}else{
return;
}
System.out.println(threadname + "-> Added! Key: " + key + " Value: " + value);
// Showing
showItems(threadname);
}
// Bewares of doublicate keys in the keylist
private boolean isAlreadyAdded(String key) {
int size = keys.size();
for (int i = 0; i < size; i++) {
if (keys.get(i).equals(key)) {
return true;
}
}
return false;
}
// Prints out all Integer with their keys
private void showItems(String threadname) {
Set<String> keys = table.keySet();
for (String key : keys) {
System.out.println(threadname + "-> Key: " + key + " Value: " + table.get(key));
}
System.out.print(System.getProperty("line.separator"));
}
// Mainmethod
public static void main(String[] args) {
final Threadexample tex = new Threadexample();
final String[] keyarray = new String[] { "Zero", "One", "Two" };
// starts 3 Threads which are adding and showing the Objects
for (int i = 0; i < 3; i++) {
final int value = i;
new Thread() {
public void run() {
setName("Thread: " + (value + 1));
tex.addItem(keyarray[value], value, getName());
}
}.start();
try {
// Leave every Thread enough time to work
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
}
Upvotes: 4
Reputation: 662
You will need to use semaphore for synchronation. Here is an exemple : http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html
Upvotes: 1