JAVA多线程之间使用管道进行通讯的小问题

在看书时遇到的一个小问题

他说,当没有数据被写入时,读线程阻塞在length=in.read(buffer),
这里的阻塞是说线程一直执行length=in.read(buffer),直到length!=-1,还得是说线程被wait或sleep了

 package test6;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

//线程之间通过管道传递数据
public class Test {

    public static void main(String[] args) throws IOException {
        PipedInputStream input = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        input.connect(out);

        Test test = new Test();
        ThreadA threadA = test.new ThreadA(out);
        ThreadB threadB = test.new ThreadB(input);
        threadA.start();
        threadB.start();


    }

    //向管道内写入数据的线程
    public class ThreadA extends Thread{

        private PipedOutputStream out; 

        public ThreadA(PipedOutputStream out) {
            this.out = out;
        }
        @Override
        public void run() {
            while(true){
                System.out.println("写数据线程在执行");
                try {
                    out.write("你好".getBytes());
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    //向管道内读数据的线程
    public class ThreadB extends Thread{
        private PipedInputStream in;
        public ThreadB(PipedInputStream in) {
            this.in= in;
        }
        @Override
        public void run() {
            while(true){
                System.out.println("读数据线程在执行");
                try {
                    byte[] buffer = new byte[1024];
                    int length = 0;
                    while(-1 != (length = in.read(buffer))){
                        System.out.println(new String(buffer, 0, length));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


}

阻塞一般是wait,系统会切换CPU,同时有数据的时候触发阻塞,让线程开始处理读取数据,操作系统会帮你处理这些。