Reputation: 191
I have a setup where I have 2 different groups of threads performing 2 separate tasks (for those wondering, group 1 calculates SHA-256 Hashes of strings, and the second group compares those hashes to ones in a dictionary). Logically what I want to happen is have all the group 2 threads created, have them wait, then as each group 1 thread computes a hash have all the group 2 threads "wake up" and check the computed hash to check for a match. This is my code for the group 2 thread using a shared dictionary of computed hashes called "shared"
private static class Group2Th implements Runnable {
private String dbUser;
private String dbHashedPass;
private SharedDict shared;
public Group2Th(String dbUser, String dbHashedPass, SharedDict shared) {
this.dbUser = dbUser;
this.dbHashedPass = dbHashedPass;
this.shared = shared;
}
public void run() {
System.out.println("Hello from G2 Thread: " + this.dbUser + " ==> " + this.dbHashedPass);
}
}
How would I go about making this thread wait until something in the "shared" dictionary of hashes gets added?
Upvotes: 0
Views: 112
Reputation: 2006
Using BlockingQueue we can achieve this task. As per Java Doc "A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. "
More Info enter link description here
Upvotes: 0
Reputation: 692281
This looks like a typical producer/consumer program. It's typically solved by sharing a BlockingQueue
among the producer threads and the consumer threads.
Producer threads put values in the queue, and consumer threads get them from the queue. The consumer thread is blocked by the queue until an element is available. The producer threads can also be blocked by the queue if the queue contains too many elements.
Upvotes: 1