2013-02-23 105 views
-3

我有以下程序,我希望有3个线程的吸烟者等待代理。我正在尝试使用CountDown锁存器来实现这一点。为什么我的第二个线程没有运行?

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(); 
      } 

对于当我运行Pam.run用下面的代码,它只是冻结在latch.await某种原因,我的线程不运行的其余部分。所以我的问题是我如何正确地做到这一点,以便前3名吸烟者等待latch.countdown();由代理线程调用。

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(); 
     } 
+3

因为你不*有*任何线程。 - > http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html – 2013-02-23 20:40:13

+0

雅不知道为什么我想我不需要明确定义线程 – 2013-02-23 21:38:52

回答

3

您应该创建一个Thread并通过Runnable实例作为参数。此外,您应该拨打start功能,而不是run。更改您的代码

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

信息:Defining and Starting a Thread

+0

由于某种原因,我认为通过实现runnable和调用run方法会隐式创建/运行线程。感谢您的支持 – 2013-02-23 21:38:29

+0

@AustinDavis欢迎您 – 2013-02-23 21:40:23

相关问题