zoukankan      html  css  js  c++  java
  • Java管道流学习

    管道流

    作用:用于线程之间的数据通信
    管道流测试:一个线程写入,一个线程读取

    import java.io.IOException;
    import java.io.PipedInputStream;
    import java.io.PipedOutputStream;
    
    public class PipedStreamDemo {
    
    	public static void main(String[] args) {
    		PipedInputStream pin = new PipedInputStream();
    		PipedOutputStream pout = new PipedOutputStream();
    
    		try {
    			pin.connect(pout);// 输入流与输出流链接
    		} catch (Exception e) {
    			e.printStackTrace();// 这是便于调试用的,上线的时候不需要
    		}
    
    		new Thread(new ReadThread(pin)).start();
    		new Thread(new WriteThread(pout)).start();
    
    		// 输出结果:读到: 一个美女。。
    	}
    }
    
    // 读取数据的线程
    class ReadThread implements Runnable {
    	private PipedInputStream pin;// 输入管道
    
    	public ReadThread(PipedInputStream pin) {
    		this.pin = pin;
    	}
    
    	@Override
    	public void run() {
    		try {
    			byte[] buf = new byte[1024];
    			int len = pin.read(buf);// read阻塞
    
    			String s = new String(buf, 0, len);
    			System.out.println("读到: " + s);
    			pin.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}// run
    }// ReadThread
    
    // 写入数据的线程
    class WriteThread implements Runnable {
    	private PipedOutputStream pout;// 输出管道
    
    	public WriteThread(PipedOutputStream pout) {
    		this.pout = pout;
    	}
    
    	@Override
    	public void run() {
    		try {
    			pout.write("一个美女。。".getBytes());// 管道输出流
    			pout.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}// run
    }// WriteThread
  • 相关阅读:
    ThreadStatic特性
    Java实现数据批量导入mysql数据库
    农业银行网上支付平台-商户接口编程-demo调试
    abp学习(四)——根据入门教程(aspnetMVC Web API进一步学习)
    abp学习(三)——文档翻译一
    eclipse快捷键
    js入门(一)
    PHP验证码显示不出来
    php 上传文件
    PHP输出控制函数(ob系列函数)
  • 原文地址:https://www.cnblogs.com/zxfei/p/10887157.html
Copyright © 2011-2022 走看看