import java.util.Random; import java.io.*; /** Simple program for generating output to standard output and error streams, * randomly intermixed. */ public class GenOutput implements Runnable { /** Main program. * @param args command line arguments: label and count. */ public static void main(String[] args) { if (args.length != 2) { System.err.println("usage: java GenOutput label byte-count"); return; } String label = args[0]; int count = Integer.parseInt(args[1]); Thread t1 = new Thread(new GenOutput(true, label, count)); Thread t2 = new Thread(new GenOutput(false, label, count)); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } // main(String[]) /** Source of random numbers. */ Random rand = new Random(); // Instance variables for this GenOutput thread /** If true, send data to System.err, otherwise System.out. */ private boolean useErrorStream; /** Label to print at the start of each line of output. */ private String label; /** Total amount of data to generate. */ private int byteCount; // Methods /** Create an instance of GenOutput. * @param err if true, send data to System.err, otherwise System.out. * @param label label to print at the start of each line of output. * @param count total number of bytes of data to generate. */ private GenOutput(boolean err, String label, int count) { this.useErrorStream = err; this.label = label; this.byteCount = count; } // GenOutput(boolean,String,int) /** Generate another line of data. * @param i the line number. * @return the next line of output. */ private byte[] genData(int i) { if (useErrorStream) { return (label + " stderr line " + i + " ABCDEFGHIJKLMNOPQRSTUVWXYZ\n" ).getBytes(); } else { return (label + " stdout line " + i + " abcdefghijklmnopqrstuvwxyz\n" ).getBytes(); } } // genData(int) /** Main loop for generating output to one stream. */ public void run() { try { OutputStream out // Output stream to use = useErrorStream ? System.err : System.out; int totalGenerated = 0; // number of bytes generated thus far byte[] data = null; // next line of output int offset = 0; // current offset in data buffer int bytesLeft = 0; // bytes remaining in data buffer int line = 0; // current line number while (totalGenerated < byteCount) { // Output one "chunk" of data int chunk = rand.nextInt(100); if (chunk + totalGenerated > byteCount) { chunk = byteCount - totalGenerated; } totalGenerated += chunk; while (chunk > 0) { if (bytesLeft == 0) { data = genData(++line); offset = 0; bytesLeft = data.length; } int n = chunk; // amount to write if (n > bytesLeft) { n = bytesLeft; } out.write(data, offset, n); offset += n; bytesLeft -= n; chunk -= n; } try { Thread.sleep(100); // 100 milliseconds } catch (InterruptedException e) { e.printStackTrace(); } } // while (totalGenerated < byteCount) out.write((byte)'\n'); } catch (IOException e) { e.printStackTrace(); } } // run() } // GenOutput