【发布时间】:2013-05-05 11:56:09
【问题描述】:
美好的一天!
我需要使用信号量来解决同步问题。我已经阅读了很多教程,现在我知道我应该使用发布方法和获取方法,但是,我不知道在代码中的何处使用它们。你能帮我或把我链接到一个有用的教程吗? 我有班级帐号:
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;
}
}
我有两个线程: 存款人:
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();
}
}
}
【问题讨论】:
-
您能解释一下信号量对帐户有何帮助吗?他们通常使用您所拥有的锁来实现。顺便说一句,通常钱会从某个地方转移到其他地方。它不像您在示例中那样创建或销毁。
-
@PeterLawrey 您可以存入支票并在 ATM 取款 ;-)
-
我建议先尝试本地化问题并尽可能发布简短的代码。
-
信号量通常用于您希望将并发事物的数量限制为固定限制的情况。假设您只想允许最多 5 个线程向打印服务发送消息,那么具有 5 个可用许可的 Semaphore 可能是一个不错的选择。由于我相信您最多只希望一个线程来修改帐户,因此我认为 Semaphore 不适合。您可以改用 Lock 对象,但您似乎已经同步了存款和取款方法以保护并发访问。你能描述一下为什么你认为信号量适合这个问题吗?
-
@cmbaxter 最初我被要求使用块同步或方法同步,这就是我所做的。然而,现在我被要求使用信号量做同样的事情,虽然我知道这不是一个很好的选择,但我必须实现它:(
标签: java multithreading synchronization semaphore