FileDocCategorySizeDatePackage
RandomCharacterGenerator.javaAPI DocExample2143Thu Apr 15 21:51:40 BST 2004javathreads.examples.ch07.example1

RandomCharacterGenerator

public class RandomCharacterGenerator extends Thread implements CharacterSource

Fields Summary
private static char[]
chars
private static String
charArray
private Random
random
private CharacterEventHandler
handler
private boolean
done
private Lock
lock
private Condition
cv
Constructors Summary
public RandomCharacterGenerator()


      
        random = new Random();
        handler = new CharacterEventHandler();
    
Methods Summary
public voidaddCharacterListener(CharacterListener cl)

        handler.addCharacterListener(cl);
    
public intgetPauseTime(int minTime, int maxTime)

        return (int) (minTime + ((maxTime-minTime)*random.nextDouble()));
    
public intgetPauseTime()

        return getPauseTime(2000, 5500);
    
public voidnextCharacter()

        handler.fireNewCharacter(this,
                                (int) chars[random.nextInt(chars.length)]);
    
public voidremoveCharacterListener(CharacterListener cl)

        handler.removeCharacterListener(cl);
    
public voidrun()

        try {
            lock.lock();
            while (true) {
                try {
                    if (done) {
                        cv.await();
                    } else {
                        nextCharacter();
                        cv.await(getPauseTime(), TimeUnit.MILLISECONDS);
                    }
                } catch (InterruptedException ie) {
                    return;
                }
            }
        } finally {
            lock.unlock();
        }
    
public voidsetDone(boolean b)

        try {
            lock.lock();
            done = b;

            if (!done) cv.signal();
        } finally {
            lock.unlock();
        }