/bench/kilim/bench/ThreadPipePingPong.java
Java | 72 lines | 58 code | 8 blank | 6 comment | 3 complexity | 1b05df068ab5cb07afe2b0bc6ce06cf4 MD5 | raw file
1/* Copyright (c) 2006, Sriram Srinivasan 2 * 3 * You may distribute this software under the terms of the license 4 * specified in the file "License" 5 */ 6 7package kilim.bench; 8 9import java.io.PipedInputStream; 10import java.io.PipedOutputStream; 11 12 13// Create two threads, have a message ping pong between them using pipes. 14public class ThreadPipePingPong { 15 public static void main(String args[]) throws Exception { 16 int ntimes = args.length == 0 ? 1000 : Integer.parseInt(args[0]); 17 PipedInputStream pi_in = new PipedInputStream(); 18 PipedOutputStream pi_out = new PipedOutputStream(); 19 PipedInputStream po_in = new PipedInputStream(pi_out); 20 PipedOutputStream po_out = new PipedOutputStream(pi_in); 21 22 PongThread po = new PongThread(po_in, po_out); 23 PingThread pi = new PingThread(ntimes, pi_in, pi_out); 24 po.start(); 25 pi.start(); 26 } 27} 28 29class PingThread extends Thread { 30 int ntimes; 31 PipedInputStream in; 32 PipedOutputStream out; 33 PingThread(int n, PipedInputStream i, PipedOutputStream o) { 34 ntimes = n; 35 in = i; 36 out = o; 37 } 38 public void run() { 39 try { 40 long begin = System.currentTimeMillis(); 41 for (int i = 0; i < ntimes; i++) { 42 out.write(100); out.flush(); //ping 43 in.read(); // wait for pong 44 } 45 System.out.println("Elapsed (" + ntimes + " iters) : " + 46 (System.currentTimeMillis() - begin) + " millis"); 47 System.exit(0); 48 } catch (Exception e) { 49 e.printStackTrace(); 50 } 51 } 52} 53 54class PongThread extends Thread { 55 PipedInputStream in; 56 PipedOutputStream out; 57 58 PongThread(PipedInputStream i, PipedOutputStream o) { 59 in = i; 60 out = o; 61 } 62 public void run() { 63 try { 64 while (true) { 65 in.read(); 66 out.write(200); out.flush(); 67 } 68 } catch (Exception e) { 69 e.printStackTrace(); 70 } 71 } 72}