ShutDownHook在多线程应用程序中

时间:2011-11-21 23:51:41

标签: java multithreading shutdown-hook

我有一个应用程序,它的主要方法产生了一百个线程(假设我们模拟了一百个账号)。我正在尝试它,我希望它只是在使用Control-C进行打印时打印终止。

我读过你可以用ShutDownHooks做到这一点所以我在主方法中添加了以下内容:

Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                             System.out.println("Terminating");
                        }
        });

然而,当我跑步时,没有任何东西被打印出来。

你能不能给我一些关于我出错的地方的指导(所有线程都在for循环中声明并从调用start方法开始)?

此致 乔治

编辑:请参阅下面的代码:

银行类:

public class Bank {
 private final double[] accounts;
   public Bank(int n, double initialBalance) {
    accounts = new double[n];
    for (int i=0; i < accounts.length;i++) {
        accounts[i] = initialBalance;
    }
}
    public double getTotalBalance() {
        double sum = 0.0;
        for (int i=0; i < accounts.length; i++) {
            sum += accounts[i];
        }
        return sum;
    }
    public synchronized void transfer(int fa, int ta, double amt) throws InterruptedException{
        System.out.print(Thread.currentThread());
        if (accounts[fa] < amt){
                        wait();
                    }
        accounts[ta] -= amt;
        System.out.println("Transfer of amount: " + amt + " from: " + fa + " Transfer to: " + ta);
        accounts[fa] += amt;
        System.out.println("Total Balance: " + getTotalBalance());
        notifyAll();

}
public int size() {
    return accounts.length;
}
public double[] getAccounts(){
    return accounts;
}

}

BankTest Class:

public class BankTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
            Bank b = new Bank(100,1000);
    int i;
        long timeStart = System.currentTimeMillis();
        long j = System.currentTimeMillis();





            for (i=0; i < b.size(); i++) {
        TransferRunnable tr = new TransferRunnable(b, i, 1000,j);
        Thread t = new Thread(tr);
        t.start();

    }
           Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
                         System.out.println("Terminating");
                    }
    });


        }


    }

TransferRunnable Class:

public class TransferRunnable implements Runnable {
private Bank b;
private int fromAccount;
private double maxAmount;
private final int DELAY = 40;
private long timeStart;
public TransferRunnable(Bank b, int from, double max, long timems) {
    this.b = b;
    fromAccount = from;
    maxAmount = max;
        timeStart = timems;
}
@Override
public void run() {

        try {
        while (true) {
            int ta = (int) (b.size() * Math.random());
            double amount =  maxAmount * Math.random();
                    double[] acc = b.getAccounts();
                    b.transfer(fromAccount,ta,amount);
            Thread.sleep((int) (DELAY*Math.random()));
        }
    }
        catch (InterruptedException e) {

        }

    }

}

2 个答案:

答案 0 :(得分:0)

运行时会打印出来。您可以将System.out.flush();添加到run()方法的末尾,这样可以确保立即打印输出。

答案 1 :(得分:0)

正如其他人所说,这应该是有效的。你用的是什么操作系统?可能是CTRL+C完全终止进程而不是要求它关闭(例如SIGKILL vs SIGINT)。你能验证你发送Java进程的信号吗?

最后,作为最后的手段,您可以尝试以下Java:

if (FileDescriptor.out.valid()) {
    FileDescriptor.out.sync();
}

我怀疑这不会有任何不同!