/*****************************************************************************/
/*                                                                           */
/*                                                                           */
/*   ©Copyright  2009 – 2012 BMC Software, Inc.                              */
/*   BMC, BMC Software, the BMC logos and other BMC marks are trademarks or  */
/*   registered trademarks of BMC Software, Inc. in the U.S. and /or         */
/*   certain other countries.                                                */
/*****************************************************************************/

package com.bmc.arsys.demo.javadriver;

import java.util.Random;

/**
 * @author Yucheng Huang
 * May 24, 2007
 */
class RandomNumberThread extends Thread {
    Object waitObj;
    boolean numberAvailable = false;
    int value;
    Random rd;

    public RandomNumberThread(int randomNumberSeed) {
        waitObj = new Object();
        rd = new Random((long) randomNumberSeed);
    }

    public void setWaitObjToNull() {
        waitObj = null;
    }

    public void run() {
        try {
            while (true) {
                synchronized (waitObj) {
                    while (numberAvailable == true) {
                        try {
                            waitObj.wait();
                        } catch (InterruptedException e) {
                        }
                    }
                    value = rd.nextInt(JavaDriver.RAND_MAX);
                    numberAvailable = true;
                    waitObj.notifyAll();
                }
            }
        } catch (Exception e) {
            // System.out.println( "Interrupted Exception ...in simplethread run");
        }

    }

    public int getRandomNumber() {
        int val = 0;

        synchronized (waitObj) {
            while (numberAvailable == false) {
                try {
                    waitObj.wait();
                } catch (InterruptedException e) {
                }
            }
            numberAvailable = false;
            waitObj.notifyAll();
            val = value;
        }
        return val;
    }
}
