`

管道流 PiperStream 的应用--------多线程

阅读更多

TestPiperStream.java

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *管道流PiperStream:在多线程中实现IO操作
 * @author HaoWang
 */
public class TestPiperStream {
    public static void main(String[] args) throws IOException {
        Sender s = new Sender();
        Receiver r = new Receiver();
        PipedOutputStream pos = s.getPOS();
        PipedInputStream pis = r.getPIS();
        pos.connect(pis);
        s.start();
        r.start();
    }
}
class Sender extends Thread {
    private PipedOutputStream pos = new PipedOutputStream();//用于向外发送数据
    public PipedOutputStream getPOS() {
        return pos;
    }

    @Override
    public void run() {
        String info = "Hello,receiver!你好";
        try {
            pos.write(info.getBytes("utf-8"));
            pos.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }

}

class Receiver extends Thread {
    private PipedInputStream pis = new PipedInputStream();
    public PipedInputStream getPIS() {
        return pis;
    }

    @Override
    public void run() {
        byte[] buf = new byte[1024];
        int b = -1;
        try {
            while((b=pis.read(buf))!=-1) {
                System.out.print(new String(buf,"utf-8"));
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
}

  

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics