File

PipedReader PipedWriter example

In this example we shall show you how to use the PipedReader and the PipedWriter. The PipedReader is a class for reading piped character-input streams, whereas the PipedWriter is a class for writing to piped character-output streams. To use the PipedReader and the PipedWriter we have performed the following steps:

  • We have created a thread, MyThread that extends the Thread. It has a PipedReader and a PipedWriter property. It overrides the run() API method of Thread. In the method, according to the thread name, it uses either the PipedReader to read or the PipedWriter to write,
  • We create a new PipedReader and a new PipedWriter and create two new instances of MyThread using the PipedReader and the PipedWriter.
  • We cause the first thread’s execution to start first, and then the second thread’s execution,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

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;
    }

    @Override
    public void run() {

  try {


if (getName().equals("Thread 1")) {


    for (int cnt = 0; cnt < 15; cnt++) {



  pw.write("Thread 1" + cnt + "n");


    }



    pw.close();


} else {


    int item;


    while ((item = pr.read()) != -1) {



  System.out.print((char) item);


    }



    pr.close();


}

  } catch (IOException e) {

  }
    }
}

public class PipedThreads {

    public static void main(String[] args) throws Exception {

  PipedWriter pw = new PipedWriter();

  PipedReader pr = new PipedReader(pw);


  MyThread mt1 = new MyThread("Thread 1", pr, pw);

  MyThread mt2 = new MyThread("Therad 2", pr, pw);


  mt1.start();


  Thread.sleep(2000);

  mt2.start();
    }
}

Output:

Thread 1 0
Thread 1 1
Thread 1 2
Thread 1 3
Thread 1 4
Thread 1 5
Thread 1 6
Thread 1 7
Thread 1 8
Thread 1 9
Thread 1 10
Thread 1 11
Thread 1 12
Thread 1 13
Thread 1 14

 
This was an example of the PipedReader and the PipedWriter in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button