Java pipeline stream PipedOutputStream and PipedInputStream basic operations

Source: Internet
Author: User

Java pipeline streams must be used in combination with PipedOutputSream and PipedInputStream. Pipeline streams are mainly used for communication between threads.

Code on

import java.io.*;public class PipeStreamDemo{public static void main(String[] args){PipedOutputStream out=null;PipedInputStream in=null;Sender sender=new Sender();Receiver receiver=new Receiver();out=sender.getOutputStream();in=receiver.getInputStream();try {out.connect(in);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}sender.start();receiver.start();}}class Sender extends Thread{private PipedOutputStream out=new PipedOutputStream();public PipedOutputStream getOutputStream(){return out;}public void run(){String str="Hello, my name is cjc!";try {out.write(str.getBytes());out.close();System.out.println("The sender Thread sends string \""+str+"\".");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}class Receiver extends Thread{private PipedInputStream in=new PipedInputStream();public PipedInputStream getInputStream(){return in;}public void run(){byte[] b=new byte[1024];try {int num=in.read(b);in.close();if(num==-1){System.out.println("The receiver Thread receives nothing!!!");}else{System.out.println("The receiver Thread receices \""+new String(b,0,num)+"\".");}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.