Java关闭钩子问题
我的关机挂钩无法运行。shutdown钩子用于在程序终止后打印所有已运行线程的统计信息。哲学家类扩展了线程,并根据是否有叉子简单地咀嚼和进食。这是我的密码Java关闭钩子问题,java,hook,shutdown,Java,Hook,Shutdown,我的关机挂钩无法运行。shutdown钩子用于在程序终止后打印所有已运行线程的统计信息。哲学家类扩展了线程,并根据是否有叉子简单地咀嚼和进食。这是我的密码 public class Main { private static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>(); public static void main(String[] args) { int cou
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.");
}
}
}
公共类主{
私有静态ArrayList=新ArrayList();
公共静态void main(字符串[]args){
int计数器=0;
int num=Integer.parseInt(args[0]);//要创建的线程数
对于(int x=0;x
感谢您提供的任何帮助,我非常感谢。您正在创建
哲学家
实例,但没有将它们添加到列表
,因此列表仍然为空,您的关闭挂钩似乎无法运行,因为它不会将任何内容打印到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.
}
您正在创建
哲学家
实例,但没有将它们添加到列表
,因此该列表保持为空,并且您的关闭挂钩似乎没有运行,因为它不会将任何内容打印到标准输出
编辑
在您最近的评论之后,我建议的下一件事是添加日志,以证明所有线程都在终止。例如,您可以从主线程连接每个哲学家线程,这样当主线程终止时,您就可以确定每个哲学家线程之前都已终止
// 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.
}
很抱歉,我试图删除尽可能多的代码以使其更易于阅读,但无意中删除了这一行。我正在向程序中的列表中添加代码,但它仍然不起作用。很抱歉,我试图删除尽可能多的代码以使其更易于阅读,但无意中删除了该行。我正在我的程序中添加列表,但它仍然不起作用。该程序正常存在,无需您干预?如果不执行phil.start,会发生什么?是什么导致哲学家线程最终终止?程序实际上是如何停止运行的?叉子是有限的资源吗?程序正常存在,无需您干预?如果不执行phil.start,会发生什么?是什么导致哲学家线程最终终止?程序实际上是如何停止运行的?叉子是有限的资源吗?