美好的一天!使用信號量進行多線程處理
我需要使用信號量解決同步問題。我讀過很多教程,現在我知道我應該使用釋放方法並獲取方法,但是,我不知道在代碼中使用它們的位置。你能幫我一下,或者聯繫我一個有用的教程。 我有類賬戶:
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;
}
}
我有兩個線程:Depositer:
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);
}
}
}
而且Withdrawer:
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();
}
}
}
你能解釋信號量如何對帳戶有幫助嗎?他們通常使用通常使用的鎖來實現。 BTW通常錢從某個地方轉移到別的地方。它不會像您在示例中那樣創建或銷燬。 – 2013-05-05 12:08:45
@PeterLawrey您可以存入支票並在ATM取款;-) – assylias 2013-05-05 12:09:46
我建議嘗試先將問題本地化,然後以短代碼的形式發佈。 – 2013-05-05 12:15:58