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 therun()
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.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | 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.