// 口座クラス
class Account{
private int balance = 0;
synchronized void deposit( int amount ){
int a = balance;
a = a + amount;
try{
Thread.sleep((int)(Math.random()*10));
}catch(Exception e){}
balance = a;
}
int getBalance(){
return balance;
}
}
// 顧客クラス
class Customer extends Thread{
Account account;
// コンストラクタ
Customer(Account account){
this.account = account;
}
// 10円ずつ貯金することを1000回繰り返す
public void run(){
for( int i = 0 ; i < 1000 ; i++ ){
account.deposit(10);
}
}
}
class Test{
public static void main(String args[]){
// 口座を作る
Account account = new Account();
// 10人の顧客を作る
Customer customers[] = new Customer[10];
// 10人の顧客が1つの口座に振り込み処理を開始する
for( int i = 0 ; i < 10 ; i++ ){
customers[i] = new Customer(account);
customers[i].start();
}
// 10人のスレッドが終わるのを待つ
try{
for( int i = 0 ; i < 10 ; i++ ){
customers[i].join();
}
}catch(Exception e){
System.err.println("Error:"+e);
}
// 残高表示
System.out.println("残高:"+account.getBalance());
}
}
|
// 口座クラス
class Account{
private int balance = 0;
void deposit( int amount ){
int a = balance;
a = a + amount;
try{
Thread.sleep((int)(Math.random()*10));
}catch(Exception e){}
balance = a;
}
int getBalance(){
return balance;
}
}
// 顧客クラス
class Customer extends Thread{
Account account;
// コンストラクタ
Customer(Account account){
this.account = account;
}
// 10円ずつ貯金することを1000回繰り返す
public void run(){
for( int i = 0 ; i < 1000 ; i++ ){
account.deposit(10);
}
}
}
class Test{
public static void main(String args[]){
// 口座を作る
Account account = new Account();
// 10人の顧客を作る
Customer customers[] = new Customer[10];
// 10人の顧客が1つの口座に振り込み処理を開始する
for( int i = 0 ; i < 10 ; i++ ){
customers[i] = new Customer(account);
customers[i].start();
}
// 10人のスレッドが終わるのを待つ
try{
for( int i = 0 ; i < 10 ; i++ ){
customers[i].join();
}
}catch(Exception e){
System.err.println("Error:"+e);
}
// 残高表示
System.out.println("残高:"+account.getBalance());
}
}
|