/bench/kilim/bench/ThreadPipePingPong.java

http://github.com/kilim/kilim · 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. package kilim.bench;
  7. import java.io.PipedInputStream;
  8. import java.io.PipedOutputStream;
  9. // Create two threads, have a message ping pong between them using pipes.
  10. public class ThreadPipePingPong {
  11. public static void main(String args[]) throws Exception {
  12. int ntimes = args.length == 0 ? 1000 : Integer.parseInt(args[0]);
  13. PipedInputStream pi_in = new PipedInputStream();
  14. PipedOutputStream pi_out = new PipedOutputStream();
  15. PipedInputStream po_in = new PipedInputStream(pi_out);
  16. PipedOutputStream po_out = new PipedOutputStream(pi_in);
  17. PongThread po = new PongThread(po_in, po_out);
  18. PingThread pi = new PingThread(ntimes, pi_in, pi_out);
  19. po.start();
  20. pi.start();
  21. }
  22. }
  23. class PingThread extends Thread {
  24. int ntimes;
  25. PipedInputStream in;
  26. PipedOutputStream out;
  27. PingThread(int n, PipedInputStream i, PipedOutputStream o) {
  28. ntimes = n;
  29. in = i;
  30. out = o;
  31. }
  32. public void run() {
  33. try {
  34. long begin = System.currentTimeMillis();
  35. for (int i = 0; i < ntimes; i++) {
  36. out.write(100); out.flush(); //ping
  37. in.read(); // wait for pong
  38. }
  39. System.out.println("Elapsed (" + ntimes + " iters) : " +
  40. (System.currentTimeMillis() - begin) + " millis");
  41. System.exit(0);
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }
  47. class PongThread extends Thread {
  48. PipedInputStream in;
  49. PipedOutputStream out;
  50. PongThread(PipedInputStream i, PipedOutputStream o) {
  51. in = i;
  52. out = o;
  53. }
  54. public void run() {
  55. try {
  56. while (true) {
  57. in.read();
  58. out.write(200); out.flush();
  59. }
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. }