目錄:系統(tǒng)學(xué)習(xí) Java IO---- 目錄交洗,概覽
PipedInputStream 類使得可以作為字節(jié)流讀取管道的內(nèi)容吞杭。 管道是同一 JVM 內(nèi)的線程之間的通信通道。
使用兩個已連接的管道流時,要為每個流操作創(chuàng)建一個線程敛助,
read() 和 write() 都是阻塞方法捻浦,如果一個線程同時讀寫就會造成死鎖
看一個例子:
public class Pipe {
public static void main(String[] args) throws IOException {
final PipedOutputStream output = new PipedOutputStream();
final PipedInputStream input = new PipedInputStream(output);
// 寫線程晤揣,創(chuàng)建匿名 Runnable 對象
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
output.write("Hello Pipe".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
});
// 讀線程,用一下 Lambda 表達(dá)式創(chuàng)建匿名 Runnable 對象
Thread thread2 = new Thread(() -> {
try {
int data = input.read();
while (data != -1) {
System.out.print((char) data);
data = input.read();
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
);
thread1.start();
thread2.start();
}
}
這里通過利用構(gòu)造方法來直接指定管道輸入流的管道輸出流。
PipedInputStream input = new PipedInputStream(output);
也可以使用 pipe1.connect(pipe2) 來連接兩個管道流朱灿,例如:
PipedInputStream pis = new PipedInputStream(); pis.connect(pos);
除了管道之外昧识,還有許多其他方法可以在同一個 JVM 中進(jìn)行通信。
事實(shí)上,線程更經(jīng)常交換完整的對象而不是原始的字節(jié)數(shù)據(jù)盗扒。
但是如果需要在線程之間交換原始字節(jié)數(shù)據(jù)跪楞,Java IO 的管道是能做到的。