주된 방법으로 100 개의 스레드를 생성하는 응용 프로그램이 있습니다 (백 개의 계정을 시뮬레이트한다고 가정 해 봅시다). 나는 그것을 실험하고 Control-C를 사용하여 intterupted 할 때 인쇄를 종료하고 싶습니다.다중 스레드 응용 프로그램의 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