FileDocCategorySizeDatePackage
RandomCharacterGenerator.javaAPI DocExample1778Mon Apr 05 13:41:50 BST 2004javathreads.examples.ch05.example2

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 AtomicBoolean
done
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()

        while (true) {
            try {
                if (done.get()) {
                    Thread.sleep(100);
                } else {
                    nextCharacter();
                    Thread.sleep(getPauseTime());
                }
            } catch (InterruptedException ex) {
                return;
            }
        }
    
public voidsetDone(boolean b)

        done.set(b);