繁体   English   中英

Java关闭挂钩问题

[英]Java Shutdown Hook Issues

我的关闭挂钩将无法运行。 在程序终止所有正在运行的哲学家线程之后,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.");
        }
    }
}

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

您正在创建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.
}

暂无
暂无

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

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