解答例 - 実習課題2 - 3.スレッドの排他制御
(実習課題2)
実習課題1のAccountクラスを修正し、最終的な残高が正しく20000円になるようにしなさい。
解答例
/**
* AccountThreadExample.java
* TECHSCORE Java マルチスレッドプログラミング3章 実習課題2
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.thread.chapter3.exercise2;
public class AcccountThreadExample implements Runnable {
private Account account = null;
public static void main(String[] args) {
//aさん
AcccountThreadExample a = new AcccountThreadExample();
//bさん
AcccountThreadExample b = new AcccountThreadExample();
//口座
Account account = new Account();
a.setAccount(account);
b.setAccount(account);
Thread threadA = new Thread(a);
Thread threadB = new Thread(b);
//aさんが口座に入金する
threadA.start();
//bさんが口座に入金する
threadB.start();
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep((long) (Math.random() * 1000)); //1秒以下のランダムな時間
} catch (InterruptedException e) {
e.printStackTrace();
}
//1000円預金する
this.getAccount().deposit(1000);
//残高を表示する
this.getAccount().showBalance();
}
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
/**
* Account.java
* TECHSCORE Java マルチスレッドプログラミング3章 実習課題2
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.thread.chapter3.exercise2;
public class Account {
private int balance = 0;
//synchronizedメソッドに変更
synchronized public void deposit(int money) {
int total = balance + money;
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
}
balance = total;
}
public void showBalance() {
System.out.println("現在の残高は " + balance + " 円です。");
}
}

