Skip to content

Instantly share code, notes, and snippets.

@djodjoni
Created March 1, 2019 21:53
Show Gist options
  • Select an option

  • Save djodjoni/d5c749f39b81d03a9e77cbe31624aa55 to your computer and use it in GitHub Desktop.

Select an option

Save djodjoni/d5c749f39b81d03a9e77cbe31624aa55 to your computer and use it in GitHub Desktop.

Revisions

  1. djodjoni created this gist Mar 1, 2019.
    53 changes: 53 additions & 0 deletions piped stream java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    public class PipedStreamExample {
    public static void main(String[] args) throws IOException, InterruptedException {

    final PipedInputStream pipedInputStream=new PipedInputStream();
    final PipedOutputStream pipedOutputStream=new PipedOutputStream();

    /*Connect pipe*/
    pipedInputStream.connect(pipedOutputStream);

    /*Thread for writing data to pipe*/
    Thread pipeWriter=new Thread(new Runnable() {
    @Override
    public void run() {
    for (int i = 65; i < 91; i++) {
    try {
    pipedOutputStream.write(i);
    Thread.sleep(500);
    } catch (IOException | InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    });

    /*Thread for reading data from pipe*/
    Thread pipeReader=new Thread(new Runnable() {
    @Override
    public void run() {
    for (int i = 65; i < 91; i++) {
    try {
    System.out.print((char)pipedInputStream.read());
    Thread.sleep(1000);
    } catch (InterruptedException | IOException e) {
    e.printStackTrace();
    }
    }
    }
    });

    /*Start thread*/
    pipeWriter.start();
    pipeReader.start();

    /*Join Thread*/
    pipeWriter.join();
    pipeReader.join();

    /*Close stream*/
    pipedOutputStream.close();
    pipedInputStream.close();

    }
    }