美好的一天!使用信号量进行多线程处理
我需要使用信号量解决同步问题。我读过很多教程,现在我知道我应该使用释放方法并获取方法,但是,我不知道在代码中使用它们的位置。你能帮我一下,或者联系我一个有用的教程。 我有类账户:
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