I have the following program where I would like to have 3 threads the smokers wait for the agent. I'm trying to use the CountDown latch to implement this.
public void runThreads(){
int numofTests;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of iterations to be completed:");
numofTests = Integer.parseInt(in.nextLine());///Gets the number of tests from the user
Agent agent = new Agent();
Smoker Pam = new Smoker ("paper", "Pam");
Smoker Tom = new Smoker ("tobacco", "Tom");
Smoker Matt = new Smoker ("matches", "Matt");
for(int i = 0; i < numofTests; i++){ //passes out as many rounds as the user specifies
Pam.run();
Tom.run();
Matt.run();
agent.run();
}
For some reason when I run Pam.run with the following code it just freezes on latch.await, and the rest of my threads don't run. So my question is how can i properly make it so that the first 3 smokers wait for the latch.countdown(); called by the agent thread.
public class Smoker implements Runnable{
String ingredient; //This is the one ingredient the smoker starts out with
String name;
public static CountDownLatch latch = new CountDownLatch(1);
int numOfSmokes = 0; //Total number of cigs smoker smoked;
public Smoker(String ingredient1, String Name)
{
ingredient1 = ingredient;
name = Name;
}
public void run(){
try {
System.out.println(this.name + " waits on the table...");
latch.await();///waits for agent to signal that new ingredients have been passed out
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println(this.name + " stops waiting and checks the table...");
checkTable();
}