Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Program {
- public static final int TOTAL_ITERATIONS = 1000000;
- private static final int NUM_ACCOUNTS = 2;
- public static void main(String[] args) {
- Bank bank = new Bank(NUM_ACCOUNTS);
- Thread accountTransfer1 = new Thread(new AccountTransferRunnable(bank));
- Thread accountTransfer2 = new Thread(new AccountTransferRunnable(bank));
- accountTransfer1.start();
- accountTransfer2.start();
- try {
- accountTransfer1.join();
- accountTransfer2.join();
- } catch (InterruptedException ex) {
- //
- }
- }
- }
- public class Account {
- private int mBalance;
- public Account() {
- mBalance = 0;
- }
- public int getBalance() {
- return mBalance;
- }
- public void withdraw(int value) {
- mBalance -= value;
- }
- public void deposit(int value) {
- mBalance += value;
- }
- }
- public class Bank {
- private List<Account> mAccounts;
- private int mSlots;
- public Bank(int slots) {
- mAccounts = new ArrayList<Account>(Collections.nCopies(slots, new Account()));
- mSlots = slots;
- }
- public int getSlots() {
- return mSlots;
- }
- public int getBalance(int id) {
- Account account = mAccounts.get(id);
- synchronized(account) {
- return account.getBalance();
- }
- }
- public void withdraw(int id, int value) {
- Account account = mAccounts.get(id);
- synchronized(account) {
- account.withdraw(value);
- }
- }
- public void deposit(int id, int value) {
- Account account = mAccounts.get(id);
- synchronized(account) {
- account.deposit(value);
- }
- }
- public void transfer(int fromId, int toId, int value) {
- Account fromAccount = mAccounts.get(fromId);
- Account toAccount = mAccounts.get(toId);
- synchronized(fromAccount) {
- synchronized(toAccount) {
- fromAccount.withdraw(value);
- toAccount.deposit(value);
- }
- }
- }
- }
- public class AccountTransferRunnable implements Runnable {
- private final Bank mBank;
- public AccountTransferRunnable(Bank bank) {
- mBank = bank;
- }
- @Override
- public void run() {
- Random random = new Random();
- int slots = mBank.getSlots();
- int fromId, toId;
- for(int i = 0; i < Program.TOTAL_ITERATIONS; i++) {
- fromId = random.nextInt(slots);
- do {
- toId = random.nextInt(slots);
- } while(toId == fromId);
- mBank.transfer(fromId, toId, 100);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement