package edu.nyu.cs9053.concurrency.chapter14.bank;

import java.util.Random;

/**
 * User: blangel
 * Date: 7/26/14
 * Time: 11:05 AM
 */
public class Deadlock {

    private Thread atm1;

    private Thread atm2;

    public void deadlock(final long durationSeconds) {
        final Bank bank = new Bank();
        final Account account1 = new Account("Foo", 1000000);
        final Account account2 = new Account("Bar", 1000000);
        final long start = System.currentTimeMillis();
        Runnable transact = new Runnable() {
            @Override public void run() {
                Random random = new Random();
                while (System.currentTimeMillis() < (start + (durationSeconds * 1000L))) {
                    if (random.nextInt(2) == 0) {
                        bank.transfer(account1, account2, random.nextInt(10));
                    } else {
                        bank.transfer(account2, account1, random.nextInt(10));
                    }
                }
            }
        };
        atm1 = new Thread(transact);
        atm2 = new Thread(transact);
        atm1.start();
        atm2.start();
    }

    public void waitForAll() throws InterruptedException {
        atm1.join();
        atm2.join();
    }

}
