其他分享
首页 > 其他分享> > 管道流 PipedInputStream和PipedOutputStream 用法

管道流 PipedInputStream和PipedOutputStream 用法

作者:互联网

注意管道流需要用到多线程

package test;
 
 
import java.io.*;
import java.sql.SQLClientInfoException;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.zip.InflaterInputStream;
 
import javax.annotation.processing.FilerException;
import javax.management.RuntimeErrorException;

import privateclass.Filterby_Name;
import privateclass.Filterby_hidden;
import privateclass.Filterby_java;
import privateclass.MyBufferedReader;
import privateclass.Person;
 
public class Main {
 
    private static final String space_operator = " ";
    private static final double pi = Math.PI;
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");
	private static final int SIZE = 1024*1024;

	/*
	 * 管道流需要配合多线程
	 * 因为单线程容易出现死锁
	 * 因为当在一个在进行另外一个就会阻塞
	 * 我们再用管道的时候一定要记得连接
	 * connect
	 */
    public static void main(String[] args) throws Exception {

    	PipedInputStream pis = new PipedInputStream();
    	PipedOutputStream pos = new PipedOutputStream();
    	pis.connect(pos);
    	Thread t1 = new Thread(new Input(pis));
    	Thread t2 = new Thread(new Output(pos));
    	t1.start();
    	t2.start();
    	
    	
    }

	
}

class Input implements Runnable
{

	private PipedInputStream pis;
	
	public Input(PipedInputStream pis) {
		super();
		this.pis = pis;
	}
	@Override
	public void run() {
		
		byte buf[] = new byte[1024];
		try {
			pis.read(buf);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String s = new String(buf);
		System.out.println(s);
	}
	
}

class Output implements Runnable
{
	private PipedOutputStream pos;
	
	public Output(PipedOutputStream pos) {
		super();
		this.pos = pos;
	}

	@Override
	public void run() {
		/*
		 * 让线程在这里睡一会
		 * 你会发现更好的观察管道之间的联系
		 */
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			pos.write("我是写入管道2333".getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

  

标签:java,PipedInputStream,pos,用法,PipedOutputStream,new,import,pis,public
来源: https://www.cnblogs.com/WINDZLY/p/11828563.html