Код: Выделить всё
public class Bank {
public static final int NUMBER_OF_ACCOUNT = 100;
private double[] accounts = new double[NUMBER_OF_ACCOUNT];
private Lock lock;
private Condition sufficientFunds;
public Bank(double total) {
double singleAmount = total / 100D;
for (int i = 0; i < NUMBER_OF_ACCOUNT; i++) {
accounts[i] = singleAmount;
}
lock = new ReentrantLock();
sufficientFunds = lock.newCondition();
}
private double getAdditionalAmount(double amount) throws InterruptedException {
Thread.sleep(1000);
return amount * 0.04D;
}
public void transfer(int from, int to, double amount) {
try {
// Not synchronized operation
double additionalAmount = getAdditionalAmount(amount);
// Acquiring lock
lock.lock();
// Verifying condition
while (amount + additionalAmount > accounts[from]) {
sufficientFunds.await();
}
// Transferring funds
accounts[from] -= amount + additionalAmount;
accounts[to] += amount + additionalAmount;
// Signaling that something has changed
sufficientFunds.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public double getTotal() {
double total = 0.0D;
lock.lock();
try {
for (int i = 0; i < NUMBER_OF_ACCOUNT; i++) {
total += accounts[i];
}
} finally {
lock.unlock();
}
return total;
}
public static void main(String[] args) {
Bank bank = new Bank(100000D);
for (int i = 0; i < 1000; i++) {
new Thread(new TransferRunnable(bank)).start();
}
}
}
< /code>
В приведенном выше примере, который поступает из основной книги Java Volume I, используется синхронизация через явные блокировки. Код явно сложно читать и подвергать ошибке. Я попытался создать об неизменные учетные записи Затем я попытаюсь использовать эти концепции, чтобы удалить синхронизацию ясной синхронизации из банка . Я разработал эти неизменные учетные записи класс:
Код: Выделить всё
class Accounts {
private final List accounts;
public Accounts(List accounts) {
this.accounts = new CopyOnWriteArrayList(accounts);
}
public Accounts(Accounts accounts, int from, int to, double amount) {
this(accounts.getList());
this.accounts.set(from, -amount);
this.accounts.set(to, amount);
}
public double get(int account) {
return this.accounts.get(account);
}
private List getList() {
return this.accounts;
}
}
Код: Выделить всё
private volatile Accounts accounts;
Код: Выделить всё
public void transfer(int from, int to, double amount) {
this.accounts = new Accounts(this.accounts, from, to, amount);
}
< /code>
Используя неизменное объект (AccountsКод: Выделить всё
BankПодробнее здесь: https://stackoverflow.com/questions/340 ... on-in-java
Мобильная версия