【问题标题】:Why is my second thread not running?为什么我的第二个线程没有运行?
【发布时间】:2013-02-23 20:37:22
【问题描述】:

我有以下程序,我想让吸烟者等待代理的 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();
        }

【问题讨论】:

标签: java multithreading synchronization countdownlatch


【解决方案1】:

您应该创建一个Thread 并将Runnable 实例作为参数传递。此外,您应该调用start 函数,而不是run。将您的代码更改为

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

信息:Defining and Starting a Thread

【讨论】:

  • 出于某种原因,我认为通过实现 runnable 并调用 run 方法,它会隐式创建/运行线程。感谢您的回答
猜你喜欢
  • 2020-10-30
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
相关资源
最近更新 更多