• java:管道流(线程间管道流)


    class Send implements Runnable{
    
    	PipedOutputStream pos = null;
    	
    	public Send()
    	{
    		this.pos = new PipedOutputStream();
    	}
    	
    	public PipedOutputStream getPipedOutputStream()
    	{
    		return this.pos;
    	}
    	
    	@Override
    	public void run() {
    		// TODO 自动生成的方法存根
    		String str = "hello world!!!";
    		try {
    			this.pos.write(str.getBytes());
    		} catch (IOException e) {
    			// TODO 自动生成的 catch 块
    			e.printStackTrace();
    		}
    		try {
    			this.pos.close();
    		} catch (IOException e) {
    			// TODO 自动生成的 catch 块
    			e.printStackTrace();
    		}
    	}
    	
    }
    
    class Receive implements Runnable{
    	
    	PipedInputStream pis = null;
    
    	public Receive(){
    		this.pis = new PipedInputStream();
    	}
    	
    	public PipedInputStream getPipedInputStream()
    	{
    		return this.pis;
    	}
    	
    	@Override
    	public void run() {
    		// TODO 自动生成的方法存根
    		byte b[] = new byte[1024];
    		int len = 0;
    		try {
    			len = this.pis.read(b);
    		} catch (IOException e) {
    			// TODO 自动生成的 catch 块
    			e.printStackTrace();
    		}
    		try {
    			this.pis.close();
    		} catch (IOException e) {
    			// TODO 自动生成的 catch 块
    			e.printStackTrace();
    		}
    		System.out.println(new String(b,0,len) );
    	}
    	
    }
    
    public class PipedOutputStreamDemo {
    
    	public static void main(String[] args) throws Exception {
    		// TODO 自动生成的方法存根
    		Send send =  new Send();
    		Receive rec = new Receive();
    		send.getPipedOutputStream().connect(rec.getPipedInputStream());
    		new Thread(send).start();
    		new Thread(rec).start();
    	}
    
    }
    

      

  • 相关阅读:
    网络设备
    Linux常用操作
    工作常用笔记
    性能测试问题总结
    mysql性能分析
    Java8新特性学习笔记-CompletableFuture
    Java语言定义的线程状态分析
    Gatling-插件开发
    RabbitMQ记录
    Go常用库
  • 原文地址:https://www.cnblogs.com/achengmu/p/7143299.html
Copyright © 2020-2023  润新知