Skip to content

Instantly share code, notes, and snippets.

@djodjoni
Created March 1, 2019 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djodjoni/d5c749f39b81d03a9e77cbe31624aa55 to your computer and use it in GitHub Desktop.
Save djodjoni/d5c749f39b81d03a9e77cbe31624aa55 to your computer and use it in GitHub Desktop.
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment