package javacodebook.thread.pipes;

import java.io.OutputStream;
import java.util.Random;

/**
 * Dieser Thread schreibt in unregelmäßigen Abständen Zahlen (Bytes) in den
 * ihm zur Verfügung gestellten OutputStream.
 *
 * @author Mark Donnermeyer
 */
class DataSource extends Thread {
    OutputStream os;
    Random random;
    
    public DataSource(OutputStream os) {
        this.os = os;
        this.random = new Random(System.currentTimeMillis());
    }
    
    public void run() {
        byte buf[] = new byte[1];
        
        try {
            // Es werden insgesamt 10 Zahlen in die Pipe geschrieben
            for (int i=0; i<10; i++) {
                // Eine neue Zufallszahl erzeugen ...
                buf[0] = (byte)random.nextInt(127);
                // .. auf der Konsole ausgeben ...
                System.out.println(buf[0]);
                // ... und in die Pipe schreiben
                os.write(buf, 0, 1);
                // Nach getaner Arbeit erst einmal pausieren.
                sleepRandomly(200, 300);
            }
            System.out.println("EOF");
            os.close();
        }
        catch (Exception ignore) {}
    }
    
    /**
     * Versetzt den Thread in einen Schlaf, der mindestens min und maximal max
     * Millisekunden dauert.
     */
    private void sleepRandomly(int min, int max) {
        try {
            int duration = random.nextInt(max-min);
            sleep(duration+min);
        }
        catch (Exception ignore) {}
    }
}
