2013-02-23 281 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

相關問題