再会!
我需要使用信号量解决同步问题。我已经阅读了很多教程,现在我知道我应该使用发布方法和获取方法,但是,我不知道在代码中的何处使用它们。你能帮我或把我链接到一个有用的教程吗?我有班级帐户:
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();
}
}
}