我有一個應用程序,它的主要方法產生了一百個線程(假設我們模擬一百個帳戶)。我正在試驗它,我希望它只是在用Control-C進行打印時打印終止。ShutDownHook在多線程應用程序
我看了你可以做到這一點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類:
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) {
}
}
}
正如我在答覆中回答的那樣,你能說出運行時系統的細節嗎? –
Windows 7與JDK 1.6.0_10 – user998388