我的關機掛鉤不會運行。關閉鉤子用於在程序終止後爲所有正在運行的哲學家線程輸出統計信息。哲學家課程擴展了線程,並且基於叉子是否可用而簡單地咀嚼和吃飯。這是我的代碼。Java關機掛鉤問題
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.");
}
}
}
感謝您提供的任何幫助,我非常感謝。
程序正常存在,您不必介入?如果你不做phil.start會發生什麼? – TofuBeer 2010-10-28 16:22:12
什麼導致哲學家線程最終終止?程序如何實際停止運行?分叉是有限的資源嗎? – Affe 2010-10-28 16:22:21