Java教程

Java 字节管道流 仿写练习

本文主要是介绍Java 字节管道流 仿写练习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import java.io.*;
public class PiperTest {
    public static void main(String[] args) throws IOException {
        PiperOutputTest send = new PiperOutputTest();
        ReceiveThread receiveThread = new ReceiveThread();
        send.getOutput().connect(receiveThread.getInput());//进行管道连接
        new Thread(send,"消息发送线程").start();
        new Thread(receiveThread,"消息接收线程").start();
    }
}
class PiperOutputTest implements Runnable{
    private PipedOutputStream output;
    public  PiperOutputTest() {
        this.output = new PipedOutputStream(); //实例化管道输出流
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try{//输出消息编辑
                this.output.write(("【第" + (i+1) + "次信息发送 -" + Thread.currentThread().getName() + " 】www.baidu.com\n").getBytes());
                Thread.sleep(1000);
            }catch (Exception e) {
                System.out.print(e.getMessage());
            }
        }
        try{
            this.output.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    public PipedOutputStream getOutput(){
        return output;
    }    
}
class ReceiveThread implements Runnable{
    private PipedInputStream input;
    public ReceiveThread() {
        // TODO Auto-generated constructor stub
        this.input = new PipedInputStream(); //实例化输出管道流
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 10; i++) {
            byte data [] = new byte [1024];
            try{
                int len = this.input.read(data) ;
                System.out.print("{"+Thread.currentThread().getName() + "接收消息}\n" + new String(data,0,len));//打印机接收的消息
            }catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        try {
            this.input.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public PipedInputStream getInput() {
        return input;
    }
}

 

这篇关于Java 字节管道流 仿写练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!