FileDocCategorySizeDatePackage
RandomCharacterGenerator.javaAPI DocExample2912Sun Dec 07 10:45:00 GMT 2003javathreads.examples.ch12.example1

RandomCharacterGenerator

public class RandomCharacterGenerator extends Thread implements CharacterSource

Fields Summary
private char[]
chars
private int
curChar
private Random
random
private CharacterEventHandler
handler
private boolean
done
private Lock
lock
private Condition
cv
private Socket
sock
private DataInputStream
reader
private DataOutputStream
writer
Constructors Summary
public RandomCharacterGenerator(String host, int port)


           
        handler = new CharacterEventHandler();
        sock = new Socket(host, port);
        reader = new DataInputStream(sock.getInputStream());
        reader.read();        // Welcome
        writer = new DataOutputStream(sock.getOutputStream());
        getString();
    
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);
    
private synchronized voidgetString()

        byte b = TypeServerConstants.GET_STRING_REQUEST;
        writer.write(b);
        writer.flush();
        b = (byte) reader.readByte();
        if (b != TypeServerConstants.GET_STRING_RESPONSE) 
            throw new IllegalStateException("Bad recv state " + b);
        String s = reader.readUTF();
        chars = s.toCharArray();
        curChar = 0;
    
public voidnextCharacter()

        handler.fireNewCharacter(this,
                                (int) chars[curChar++]);
	if (curChar == chars.length) {
	    try {
	        getString();
	    } catch (IOException ioe) {
	        // Put up a dialog box to alert user of error
	    }
        }
    
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();
        }