Java PipedInputStream solve multi thread producer consumer problem

Description

Java PipedInputStream solve multi thread producer consumer problem

import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class Main {
  public static void main(String[] args) throws Exception {
    PipedInputStream pis = new PipedInputStream();
    PipedOutputStream pos = new PipedOutputStream();
    pos.connect(pis);//from  w  w  w .  ja v a  2s . c  om
    new Thread(new Producer(pos)).start();
    new Thread(new Consumer(pis)).start();
  }
}
class Consumer implements Runnable{
  private PipedInputStream pis;

  public Consumer(PipedInputStream p) {
    pis = p;
  }
  @Override
  public void run() {
    try {
      int num = -1;
      while ((num = pis.read()) != -1) {
        System.out.println("Reading: " + num);
      }
      pis.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}
class Producer implements Runnable{
  private PipedOutputStream pos;

  public Producer(PipedOutputStream p) {
    pos = p;
  }

  @Override
  public void run() {
    try {
      for (int i = 1; i <= 5; i++) {
        pos.write((byte) i);
        pos.flush();
        System.out.println("Writing: " + i);
        Thread.sleep(500);
      }
      pos.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}



PreviousNext

Related