package edu.nyu.cs9053.concurrency.chapter14;

import java.util.Random;

/**
 * User: blangel
 * Date: 7/20/14
 * Time: 3:42 PM
 */
public class RaceCondition {

    private final Random random = new Random();

    private long value;

    public void race() throws InterruptedException {
        Runnable work = new Runnable() {
            @Override public void run() {
                while (!interrupted()) {
                    long random = (Math.abs(RaceCondition.this.random.nextLong() % 10L));
                    long expected = (value + random);
                    value += random;
                    if (value != expected) {
                        System.out.printf("Found %d != %d%n", value, expected);
                        Thread.currentThread().interrupt();
                    }
                }
            }
        };
        worker1 = new Thread(work);
        worker2 = new Thread(work);
        worker1.start();
        worker2.start();
    }

    public void waitForAll() throws InterruptedException {
        worker1.join();
        worker2.join();
    }

    private boolean interrupted() {
        return (worker1.isInterrupted() || worker2.isInterrupted());
    }
    Thread worker1;
    Thread worker2;

    public static void main(String[] args) throws InterruptedException {
        RaceCondition condition = new RaceCondition();
        condition.race();
        condition.waitForAll();
    }

}
