zoukankan      html  css  js  c++  java
  • PipedInputStream and PipedOutputStream example

    必须要有PipedInputStream ,PipedOutputStream 在不同线程,不然死锁

    Java.io.PipedOutputStream and java.io.PipedInputStream has been introduced in JDK 1.0. PipedOutputStream and PipedInputStream both are connected to each other to create a communication pipe. PipedOutputStream is the sending end and PipedOutputStream is the receiving end of the pipe. Both ends should not be handled by single thread otherwise deadlock may occur. If any thread stops working, pipe is said to be broken.

    Java PipedOutputStream and PipedInputStream Example

    public class PipedStreamExample
    {
    final static PipedOutputStream pipedOut = new PipedOutputStream();
    final static PipedInputStream pipedIn = new PipedInputStream();

    class PipedOutputThread implements Runnable{
    @Override
    public void run() {
    for(int i=1;i<=10;i++){
    try {
    pipedOut.write(("Message "+i+" ").getBytes());
    Thread.sleep(500);
    } catch (IOException e) {
    e.printStackTrace();
    }catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }

    class PipedInputThread implements Runnable{
    @Override
    public void run() {
    try {
    int i=0;
    while((i=pipedIn.read())!=-1){
    System.out.print((char)i);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    public static void main(String[] args) {
    try {
    pipedOut.connect(pipedIn);
    } catch (IOException e) {
    e.printStackTrace();
    }
    ExecutorService service = Executors.newFixedThreadPool(2);
    service.execute(new PipedStreamExample().new PipedOutputThread());
    service.execute(new PipedStreamExample().new PipedInputThread());
    }}

  • 相关阅读:
    2020/2/14
    2020/2/13
    《人类简史》
    2020/2/12
    bzoj3157国王奇遇记(秦九韶算法+矩乘)&&bzoj233AC达成
    [noip科普]关于LIS和一类可以用树状数组优化的DP
    [uva11722&&cogs1488]和朋友会面Joining with Friend
    Bzoj2154 Crash的数字表格 乘法逆元+莫比乌斯反演(TLE)
    NOIP2016滚粗记
    bzoj2228[ZJOI2011]礼物(gift)
  • 原文地址:https://www.cnblogs.com/daxiong225/p/8664826.html
Copyright © 2011-2022 走看看