本章,我们对java 管道进行学习。
转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_04.html
java 管道介绍
在java中,PipedOutputStream和PipedInputStream分别是管道输出流和管道输入流。
它们的作用是让多线程可以通过管道进行线程间的通讯。在使用管道通信时,必须将PipedOutputStream和PipedInputStream配套使用。
使
用管道通信时,大致的流程是:我们在线程A中向PipedOutputStream中写入数据,这些数据会自动的发送到与
PipedOutputStream对应的PipedInputStream中,进而存储在PipedInputStream的缓冲中;此时,线程B通过
读取PipedInputStream中的数据。就可以实现,线程A和线程B的通信。
PipedOutputStream和PipedInputStream源码分析
下面介绍PipedOutputStream和PipedInputStream的源码。在阅读它们的源码之前,建议先看看源码后面的示例。待理解管道的作用和用法之后,再看源码,可能更容易理解。
此外,由于在“java io系列03之 ByteArrayOutputStream的简介,源码分析和示例(包括OutputStream)”中已经对PipedOutputStream的父类OutputStream进行了介绍,这里就不再介绍OutputStream。
在“java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括InputStream)”中已经对PipedInputStream的父类InputStream进行了介绍,这里也不再介绍InputStream。
1. PipedOutputStream 源码分析(基于jdk1.7.40)
1 package java.io;
2
3 import java.io.*;
4
5 public class PipedOutputStream extends OutputStream {
6
7 // 与PipedOutputStream通信的PipedInputStream对象
8 private PipedInputStream sink;
9
10 // 构造函数,指定配对的PipedInputStream
11 public PipedOutputStream(PipedInputStream snk) throws IOException {
12 connect(snk);
13 }
14
15 // 构造函数
16 public PipedOutputStream() {
17 }
18
19 // 将“管道输出流” 和 “管道输入流”连接。
20 public synchronized void connect(PipedInputStream snk) throws IOException {
21 if (snk == null) {
22 throw new NullPointerException();
23 } else if (sink != null || snk.connected) {
24 throw new IOException("Already connected");
25 }
26 // 设置“管道输入流”
27 sink = snk;
28 // 初始化“管道输入流”的读写位置
29 // int是PipedInputStream中定义的,代表“管道输入流”的读写位置
30 snk.in = -1;
31 // 初始化“管道输出流”的读写位置。
32 // out是PipedInputStream中定义的,代表“管道输出流”的读写位置
33 snk.out = 0;
34 // 设置“管道输入流”和“管道输出流”为已连接状态
35 // connected是PipedInputStream中定义的,用于表示“管道输入流与管道输出流”是否已经连接
36 snk.connected = true;
37 }
38
39 // 将int类型b写入“管道输出流”中。
40 // 将b写入“管道输出流”之后,它会将b传输给“管道输入流”
41 public void write(int b) throws IOException {
42 if (sink == null) {
43 throw new IOException("Pipe not connected");
44 }
45 sink.receive(b);
46 }
47
48 // 将字节数组b写入“管道输出流”中。
49 // 将数组b写入“管道输出流”之后,它会将其传输给“管道输入流”
50 public void write(byte b[], int off, int len) throws IOException {
51 if (sink == null) {
52 throw new IOException("Pipe not connected");
53 } else if (b == null) {
54 throw new NullPointerException();
55 } else if ((off < 0) || (off > b.length) || (len < 0) ||
56 ((off + len) > b.length) || ((off + len) < 0)) {
57 throw new IndexOutOfBoundsException();
58 } else if (len == 0) {
59 return;
60 }
61 // “管道输入流”接收数据
62 sink.receive(b, off, len);
63 }
64
65 // 清空“管道输出流”。
66 // 这里会调用“管道输入流”的notifyAll();
67 // 目的是让“管道输入流”放弃对当前资源的占有,让其它的等待线程(等待读取管道输出流的线程)读取“管道输出流”的值。
68 public synchronized void flush() throws IOException {
69 if (sink != null) {
70 synchronized (sink) {
71 sink.notifyAll();
72 }
73 }
74 }
75
76 // 关闭“管道输出流”。
77 // 关闭之后,会调用receivedLast()通知“管道输入流”它已经关闭。
78 public void close() throws IOException {
79 if (sink != null) {
80 sink.receivedLast();
81 }
82 }
83 }