package edu.nyu.cs9053.concurrency.chapter14;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * User: blangel
 * Date: 7/26/14
 * Time: 9:57 AM
 */
public class WithoutCondition {

    private final Lock lock = new ReentrantLock();

    private Thread watcher;

    private Thread worker1;

    private int value;

    public void withoutCondition() {
        Runnable watch = new Runnable() {
            @Override public void run() {
                while (!interrupted()) {
                    lock.lock();
                    try {
                        if (value >= 100) {
                            watcher.interrupt();
                            worker1.interrupt();
                        } else {
                            System.out.printf("Unnecessary CPU usage (value < 100, don't want to be running)%n");
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            }
        };
        Runnable work = new Runnable() {
            @Override public void run() {
                while (!interrupted()) {
                    lock.lock();
                    try {
                        value += 1;
                    } finally {
                        lock.unlock();
                    }
                }
            }
        };
        watcher = new Thread(watch);
        worker1 = new Thread(work);
        watcher.start();
        worker1.start();
    }

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

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