简体   繁体   中英

ShutDownHook in multi-threaded application

I have an application which in its main method spawns a hundred threads (let's say we simulate a hundred accounts). I am experimenting with it and I would like it to just print terminating when intterupted with Control-C.

I read you can do that with ShutDownHooks so I added the following in my main method:

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

However, when I run it nothing gets printed.

Could you please offer me some guidance as to where I am going wrong (all threads are declared in a for loop and start with invoking their start method)?

Regards, George

EDIT: Please see below for the code:

Bank Class:

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) {

        }

    }

}

It gets printed when I run it. You could add System.out.flush(); to the end of the run() method though, this makes sure that the output is printed immediately.

as others have said, this should just work. What OS are you using? It might be that CTRL+C is killing the process completely rather than asking it to shutdown (eg SIGKILL vs SIGINT). Can you verify which signal you're sending the Java process?

Finally, as a last resort you could try the following bit of Java:

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

I suspect that this won't make any difference though!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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