Java/File Input Output/PipedWriter

Материал из Java эксперт
Перейти к: навигация, поиск

PipedReader and PipedWriter and thread

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
class MyThread extends Thread {
  private PipedReader pr;
  private PipedWriter pw;
  MyThread(String name, PipedReader pr, PipedWriter pw) {
    super(name);
    this.pr = pr;
    this.pw = pw;
  }
  public void run() {
    try {
      if (getName().equals("src")) {
        for (int i = 0; i < 15; i++)
          pw.write("src " + " A" + i + "\n"); 
        pw.close();
      } else {
        int item;
        while ((item = pr.read()) != -1)
          System.out.print((char) item); 
        pr.close();
      }
    } catch (IOException e) {
    }
  }
}
class PipedThreads {
  public static void main(String[] args) throws Exception {
    PipedWriter pw = new PipedWriter();
    PipedReader pr = new PipedReader(pw);
    MyThread mt1 = new MyThread("src", pr, pw);
    MyThread mt2 = new MyThread("dst", pr, pw);
    mt1.start();
    Thread.sleep(2000);
    mt2.start();
  }
}