简体   繁体   English

Java关闭挂钩问题

[英]Java Shutdown Hook Issues

My shutdown hooks will not run. 我的关闭挂钩将无法运行。 The shutdown hook is intended to print out statistics after the program has terminated for all philosopher threads that had been running. 在程序终止所有正在运行的哲学家线程之后,shutdown挂钩旨在打印出统计信息。 The philosopher class extends Thread, and simply chews and eats based on if forks are available or not. 哲学家类扩展了Thread,并根据叉子是否可用来简单地咀嚼和进食。 Here is my code. 这是我的代码。

public class Main {
    private static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();

public static void main(String[] args) {
    int counter = 0;
    int num = Integer.parseInt(args[0]); // number of philosopher threads to create
    for(int x = 0; x < num; x++)
    {
        Fork one = new Fork(counter);
        counter++;
        Fork two = new Fork(counter);
        counter++;
        Philosopher p = new Philosopher(String.valueOf(x), one, two); // (Identifier, fork one, fork two)
        philosophers.add(p);
    }

    // Create shutdown hook
    Stats s = new Stats(philosophers);
    Runtime.getRuntime().addShutdownHook(s);

    // Start all philosopher threads
    for(Philosopher phil : philosophers)
    {
        phil.start();
    }
}
}


public class Stats extends Thread{
    private ArrayList<Philosopher> list = new ArrayList<Philosopher>();

    public Stats(ArrayList<Philosopher> al)
    {
        list = al;
    }

    public void run()
    {
        System.out.println("Test");
        for(Philosopher p : list)
        {
            System.out.println(p.getPhilName() + " thought for " + p.getTimeThinking() + " milliseconds and chewed for " + p.getTimeChewing() + " milliseconds.");
        }
    }
}

Thanks for any help you can provide, I greatly appreciate it. 感谢您提供的任何帮助,非常感谢。

You're creating Philosopher instances but are not adding them to list , hence the list remains empty and your shut-down hook appears not to run because it won't print anything to stdout. 您正在创建Philosopher实例,但未将其添加到list ,因此该列表保持为空,并且您的关闭挂钩似乎无法运行,因为它不会向stdout打印任何内容。

EDIT 编辑

Following your recent comment the next thing I'd suggest is to add logging to prove that all threads are terminating. 在您最近发表评论之后,我建议的下一件事是添加日志记录以证明所有线程都在终止。 For example, you could join with each philosopher thread from your main thread so that when your main thread terminates you are certain that each philosopher thread has previously terminated. 例如,您可以与主线程中的每个哲学家线程一起加入,以便在主线程终止时可以确定每个哲学家线程先前都已终止。

  // Start all philosopher threads
  for (Philosopher phil : philosophers) {
    phil.start();
  }

  for (Philosopher phil : philosophers) {
    System.err.println("Joining with thread: " + phil.getName());
    phil.join();
  }

  System.err.println("Main thread terminating.");
  // Shut-down hook should now run.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM