FileDocCategorySizeDatePackage
RandomCharacterGenerator.javaAPI DocExample1582Mon Apr 05 12:47:06 BST 2004javathreads.examples.ch04.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
Constructors Summary
public RandomCharacterGenerator()


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

        handler.addCharacterListener(cl);
    
public intgetPauseTime()

        return (int) (Math.max(1000, 5000 * random.nextDouble()));
    
public voidnextCharacter()

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

        handler.removeCharacterListener(cl);
    
public synchronized voidrun()

        while (true) {
            try {
                if (done) {
                    wait();
                } else {
                    nextCharacter();
                    wait(getPauseTime());
                }
	    } catch (InterruptedException ie) {
	        return;
	    }
	}
    
public synchronized voidsetDone(boolean b)

        done = b;

        if (!done)
            notify();