Java IO 파이프 흐름

2429 단어
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class Test4 {

    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();

        //     :  :     。。
        /**     
         * ReadThread    ,      
         * WriteThread      ,  6  
         * WriteThread      
         * ReadThread    ,    
         * ReadThread  :     。。
         */
    }
}

//        
class ReadThread implements Runnable {
    private PipedInputStream pin;//     

    public ReadThread(PipedInputStream pin) {
        this.pin = pin;
    }

    @Override
    public void run() {
        try {
            byte[] buf = new byte[1024];

            System.out.println("ReadThread    ,      ");
            int len = pin.read(buf);// read  
            System.out.println("ReadThread    ,    ");

            String s = new String(buf, 0, len);
            System.out.println("ReadThread  : " + 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 {
            System.out.println("WriteThread      ,  6  ");
            Thread.sleep(6000);
            pout.write("    。。".getBytes());//      
            pout.close();
            System.out.println("WriteThread      ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }// run
}// WriteThread

좋은 웹페이지 즐겨찾기