私は喫煙者がエージェントを待つ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();
}