编程知识 cdmana.com

Java learning diary: I / O flow (3)

The main contents of this lesson are :

1. Pipe flow 

Pipe flow :

		 Used to connect input and output streams .
  		 It is usually used to transfer data between two different threads .
  		 there input It is corresponding to getting data from the pipeline and inputting it to other places .
  		output The corresponding is to get data from other places and output data to the pipeline .

PipedTest01 class ( Test pipeline ):

package LessonForIO03;

import java.io.*;

public class PipedTest01 
{
   
   
	// How to produce data , Write data to the pipeline .
	public static void outputTo(PipedOutputStream pos)
	{
   
   
		try 
		{
   
   
			for (int i=0; i<20; i++)
			{
   
   
				pos.write(i);
				pos.flush();// Every time output once , Refresh buffer , The purpose is to write out immediately .
				System.out.println(" Writing data  "+i+"  Into the pipe .");
				
				Thread.sleep(1000);//	 Every time you write , The thread stops for a second , Avoid writing too fast , Is not obvious .
			}
			
			pos.close();
		} catch (IOException | InterruptedException e)
			{
   
   
				e.printStackTrace();
			}
	}
	
	// How to get the data , Take the data out of the pipe .
	public static void inputTo(PipedInputStream pis)
	{
   
   
		try
		{
   
   
			int length;
			while ((length = pis.read()) != -1)
			{
   
   
				System.out.println(" Data read from the pipeline :"+length);
			}
			
		} catch (IOException e)
			{
   
   
				e.printStackTrace();
			}
	}
	
	public static void main(String[] args) 
	{
   
   
		// Assemble pipes through constructors :
		System.out.println(" Assemble pipes through constructors :");
		PipedInputStream pis1 = new PipedInputStream();
		PipedOutputStream pos1 = null;
		try 
		{
   
   
			pos1 = new PipedOutputStream(pis1);// It can't be used in this way lambda Expression to initialize new Thread
		} catch (IOException e) 
			{
   
   
				e.printStackTrace();
			}
		
		// adopt connect To assemble pipes :
		System.out.println(" adopt connect To assemble pipes :");
		PipedInputStream pis2 = new PipedInputStream();
		PipedOutputStream pos2 = new PipedOutputStream();
		try 
		{
   
   
			pos2.connect(pis2);// They can even do it upside down , It is recommended to use .
		} catch (IOException e)
			{
   
   
				e.printStackTrace();
			}
		
		new Thread(()->{
   
   outputTo(pos2);}).start();
		new Thread(()->{
   
   inputTo(pis2);}).start();
	}
}

 Part of the text of this article comes from :
 Mr. Yang Haibin, gudu coffee  — 《java Programming language advanced features 》
 Thank you very much for bringing me the passion of learning .

2020.11.9
 This article is my study notes , Do not carry out any commercial, so do not support reprint, please understand ! Please don't take it to business !
 If it helps you, please feel free to review !
 Just to record my learning process .
 BI 

版权声明
本文为[osc_j9nll12v]所创,转载请带上原文链接,感谢

Scroll to Top