Piped IO : PipedInputStream « File « Java Tutorial

Home
Java Tutorial
1.Language
2.Data Type
3.Operators
4.Statement Control
5.Class Definition
6.Development
7.Reflection
8.Regular Expressions
9.Collections
10.Thread
11.File
12.Generics
13.I18N
14.Swing
15.Swing Event
16.2D Graphics
17.SWT
18.SWT 2D Graphics
19.Network
20.Database
21.Hibernate
22.JPA
23.JSP
24.JSTL
25.Servlet
26.Web Services SOA
27.EJB3
28.Spring
29.PDF
30.Email
31.J2ME
32.J2EE Application
33.XML
34.Design Pattern
35.Log
36.Security
37.Apache Common
38.Ant
39.JUnit
Java Tutorial » File » PipedInputStream 
11.26.1.Piped IO
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

class PipedIOApp {
  public static void main(String args[]) {
    Thread thread1 = new Thread(new PipeOutput("Producer"));
    Thread thread2 = new Thread(new PipeInput("Consumer"));
    thread1.start();
    thread2.start();
    boolean thread1IsAlive = true;
    boolean thread2IsAlive = true;
    do {
      if (thread1IsAlive && !thread1.isAlive()) {
        thread1IsAlive = false;
      }
      if (thread2IsAlive && !thread2.isAlive()) {
        thread2IsAlive = false;
      }
    while (thread1IsAlive || thread2IsAlive);
  }
}

class PipeIO {
  static PipedOutputStream outputPipe = new PipedOutputStream();

  static PipedInputStream inputPipe = new PipedInputStream();
  static {
    try {
      outputPipe.connect(inputPipe);
    catch (IOException ex) {
      System.out.println("IOException in static initializer");
    }
  }

  String name;

  public PipeIO(String id) {
    name = id;
  }
}

class PipeOutput extends PipeIO implements Runnable {
  public PipeOutput(String id) {
    super(id);
  }

  public void run() {
    String s = "This is a test.";
    try {
      for (int i = 0; i < s.length(); ++i) {
        outputPipe.write(s.charAt(i));
        System.out.println(name + " wrote " + s.charAt(i));
      }
      outputPipe.write('!');
    catch (IOException ex) {
      System.out.println("IOException in PipeOutput");
    }
  }
}

class PipeInput extends PipeIO implements Runnable {
  public PipeInput(String id) {
    super(id);
  }

  public void run() {
    boolean eof = false;
    try {
      while (!eof) {
        int inChar = inputPipe.read();
        if (inChar != -1) {
          char ch = (charinChar;
          if (ch == '!') {
            eof = true;
            break;
          else
            System.out.println(name + " read " + ch);
        }
      }
    catch (IOException ex) {
      System.out.println("IOException in PipeOutput");
    }
  }
}
11.26.PipedInputStream
11.26.1.Piped IO
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.