Java/File Input Output/Pipes

Материал из Java эксперт
Версия от 06:02, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Pipes for Communications

 
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Pipe {
  public static void main(String args[]) throws Exception {
    PipedInputStream in = new PipedInputStream();
    PipedOutputStream out = new PipedOutputStream(in);
    Sender s = new Sender(out);
    Receiver r = new Receiver(in);
    Thread t1 = new Thread(s);
    Thread t2 = new Thread(r);
    t1.start();
    t2.start();
  }
}
class Sender implements Runnable {
  OutputStream out;
  public Sender(OutputStream out) {
    this.out = out;
  }
  public void run() {
    byte value;
    try {
      for (int i = 0; i < 5; i++) {
        value = (byte) (Math.random() * 256);
        System.out.print("About to send " + value + ".. ");
        out.write(value);
        System.out.println("..sent..");
        Thread.sleep((long) (Math.random() * 1000));
      }
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
class Receiver implements Runnable {
  InputStream in;
  public Receiver(InputStream in) {
    this.in = in;
  }
  public void run() {
    int value;
    try {
      while ((value = in.read()) != -1) {
        System.out.println("received " + (byte) value);
      }
      System.out.println("Pipe closed");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}