Java Shutdown Hook问题

时间:2010-10-28 15:53:10

标签: java hook shutdown

我的关机挂钩不会运行。关闭钩子用于在程序终止后为所有已运行的哲学家线程打印出统计信息。哲学家类扩展了Thread,并根据叉子是否可用来简单地咀嚼和吃掉。这是我的代码。

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.");
        }
    }
}

感谢您提供的任何帮助,我非常感谢。

1 个答案:

答案 0 :(得分:1)

您正在创建Philosopher个实例,但没有将它们添加到list,因此列表保持为空并且您的关闭挂钩似乎无法运行,因为它不会向stdout打印任何内容。

修改

根据您最近的评论,我建议的另一件事是添加日志记录以证明所有线程都在终止。例如,您可以从主线程中加入每个哲学家线程,这样当您的主线程终止时,您确定每个哲学家线程先前已经终止。

  // 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.
}