0

良い一日!

セマフォを使用して同期の問題を解決する必要があります。多くのチュートリアルを読み、リリース メソッドを使用する必要があり、メソッドを取得する必要があることはわかっていますが、コード内でそれらを使用する場所がわかりません。私を助けてくれるか、役に立つチュートリアルにリンクしてください。私はクラスアカウントを持っています:

public class Account {
   protected double balance;

  public synchronized void withdraw(double amount) {
    this.balance = this.balance - amount;
}

public synchronized void deposit(double amount) {
    this.balance = this.balance + amount;
}
  }

2 つのスレッドがあります。

public class Depositer extends Thread {
    // deposits $10 a 10 million times
    protected Account account;

public Depositer(Account a) {
    account = a;
}

@Override
public void run() {
    for(int i = 0; i < 10000000; i++) {
        account.deposit(10);
    }
}
}

そして引き出し:

public class Withdrawer extends Thread {

    // withdraws $10 a 10 million times
    protected Account account;

public Withdrawer(Account a) {
    account = a;
}

@Override
public void run() {
    for(int i = 0; i < 1000; i++) {
        account.withdraw(10);
    }
}
}

ここにメインがあります:

    public class AccountManager {
        public static void main(String[] args)  {           
    // TODO Auto-generated method stub

    Account [] account = new Account[2];
    Depositor [] deposit = new Depositor[2];
    Withdrawer [] withdraw = new Withdrawer[2];

    // The birth of  10 accounts
    account[0] = new Account(1234,"Mike",1000);
    account[1] = new Account(2345,"Adam",2000);

    // The birth of 10 depositors 
    deposit[0] = new Depositor(account[0]);
    deposit[1] = new Depositor(account[1]);


    // The birth of  10 withdraws 
    withdraw[0] = new Withdrawer(account[0]);
    withdraw[1] = new Withdrawer(account[1]);


            for(int i=0; i<2; i++)
            {
                deposit[i].start();
                withdraw[i].start();
            }               

    for(int i=0; i<2; i++){
        try {
            deposit[i].join();
            withdraw[i].join();
        } 
                    catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
4

2 に答える 2