-3

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();
        }
Austin Davis
  • 3,516
  • 10
  • 27
  • 47

1 Answers1

3

You should create a Thread and pass the Runnable instance as parameter. Also, you should call the start function, not run. Change your code to

(new Thread(Pam)).start();
//similar for others...

Info: Defining and Starting a Thread

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • For some reason I thought by implementing runnable and calling the run method it would implicitly create/run the thread. Thanks for the anwser – Austin Davis Feb 23 '13 at 21:38