初めて質問させていただきます。よろしくお願いします。
以下のjavaのソースコードについて、最初にbalanceに30000と入れてみて1000を5回入金、5回出金する場合、実行後に出力される数値は同じだったり異なったりしますが、例えば実行後に25000と出力された場合、Accountクラスの中のdiposit、withdrawの処理で具体的にtemp、balanceにどの様に値が入って25000と出力されているのでしょうか?
public class Account {
private long balance;
public long getBalance(){
return balance;
}
Account(long balance){
this.balance=balance;
}
void withdraw(long amount){
try{
Thread.sleep(200);
long temp = balance;
Thread.sleep(200);
temp -=amount;
Thread.sleep(200);
balance = temp;
}catch(InterruptedException e){
e.printStackTrace();
}
}
void deposit(long amount){
try{
Thread.sleep(200);
long temp = balance;
Thread.sleep(200);
temp +=amount;
Thread.sleep(200);
balance = temp;
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
-----ここから入金のプログラムです-------
public class InATMThread extends Thread {
Account ac;
InATMThread(Account ac){ this.ac = ac; } public void run(){ for (int i = 0; i < 5; i++){ ac.deposit(1000); System.out.println("1000円ふりこみました"); } }
}
-----出金のプログラムです-----
public class OutATMThread extends Thread {
Account ac;
OutATMThread(Account ac){ this.ac = ac; } public void run(){ for(int i = 0; i < 5; i++){ ac.withdraw(1000); System.out.println("1000円ひきだしました"); } } }
-----実行のプログラムです-----
public class UseATM {
public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Account ac = new Account(30000); InATMThread in = new InATMThread(ac); OutATMThread out = new OutATMThread(ac); in.start(); out.start(); try{ in.join(); out.join(); }catch(Exception e){ e.printStackTrace(); } System.out.println("残高:"+ac.getBalance()); }
}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/12/16 17:05