gpt4 book ai didi

java - 多线程应用程序中的 ShutDownHook

转载 作者:行者123 更新时间:2023-12-01 05:35:51 25 4
gpt4 key购买 nike

我有一个应用程序,它的主要方法生成一百个线程(假设我们模拟一百个帐户)。我正在试验它,我希望它在被 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;
}

}

银行测试类:

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 类:

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

}

}

}

最佳答案

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

关于java - 多线程应用程序中的 ShutDownHook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8220194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com