package java.io;
public class PipedWriter extends Writer {
// 与PipedWriter通信的PipedReader对象
private PipedReader sink;
// PipedWriter的关闭标记
private boolean closed = false;
// 构造函数,指定配对的PipedReader
public PipedWriter(PipedReader snk) throws IOException {
connect(snk);
}
// 构造函数
public PipedWriter() {
}
// 将“PipedWriter” 和 “PipedReader”连接。
public synchronized void connect(PipedReader snk) throws IOException {
if (snk == null) {
throw new NullPointerException();
} else if (sink != null || snk.connected) {
throw new IOException("Already connected");
} else if (snk.closedByReader || closed) {
throw new IOException("Pipe closed");
}
sink = snk;
snk.in = -1;
snk.out = 0;
// 设置“PipedReader”和“PipedWriter”为已连接状态
// connected是PipedReader中定义的,用于表示“PipedReader和PipedWriter”是否已经连接
snk.connected = true;
}
// 将一个字符c写入“PipedWriter”中。
// 将c写入“PipedWriter”之后,它会将c传输给“PipedReader”
public void write(int c) throws IOException {
if (sink == null) {
throw new IOException("Pipe not connected");
}
sink.receive(c);
}
// 将字符数组b写入“PipedWriter”中。
// 将数组b写入“PipedWriter”之后,它会将其传输给“PipedReader”
public void write(char cbuf[], int off, int len) throws IOException {
if (sink == null) {
throw new IOException("Pipe not connected");
} else if ((off | len | (off + len) | (cbuf.length - (off + len))) < ) {
throw new IndexOutOfBoundsException();
}
sink.receive(cbuf, off, len);
}
// 清空“PipedWriter”。
// 这里会调用“PipedReader”的notifyAll();
// 目的是让“PipedReader”放弃对当前资源的占有,让其它的等待线程(等待读取PipedWriter的线程)读取“PipedWriter”的值。
public synchronized void flush() throws IOException {
if (sink != null) {
if (sink.closedByReader || closed) {
throw new IOException("Pipe closed");
}
synchronized (sink) {
sink.notifyAll();
}
}
}
// 关闭“PipedWriter”。
// 关闭之后,会调用receivedLast()通知“PipedReader”它已经关闭。
public void close() throws IOException {
closed = true;
if (sink != null) {
sink.receivedLast();
}
}
}
package java.io;
public class PipedReader extends Reader {
// “PipedWriter”是否关闭的标记
boolean closedByWriter = false;
// “PipedReader”是否关闭的标记
boolean closedByReader = false;
// “PipedReader”与“PipedWriter”是否连接的标记
// 它在PipedWriter的connect()连接函数中被设置为true
boolean connected = false;
Thread readSide; // 读取“管道”数据的线程
Thread writeSide; // 向“管道”写入数据的线程
// “管道”的默认大小
private static final int DEFAULT_PIPE_SIZE = 1024;
// 缓冲区
char buffer[];
//下一个写入字符的位置。in==out代表满,说明“写入的数据”全部被读取了。
int in = -;
//下一个读取字符的位置。in==out代表满,说明“写入的数据”全部被读取了。
int out = ;
// 构造函数:指定与“PipedReader”关联的“PipedWriter”
public PipedReader(PipedWriter src) throws IOException {
this(src, DEFAULT_PIPE_SIZE);
}
// 构造函数:指定与“PipedReader”关联的“PipedWriter”,以及“缓冲区大小”
public PipedReader(PipedWriter src, int pipeSize) throws IOException {
initPipe(pipeSize);
connect(src);
}
// 构造函数:默认缓冲区大小是1024字符
public PipedReader() {
initPipe(DEFAULT_PIPE_SIZE);
}
// 构造函数:指定缓冲区大小是pipeSize
public PipedReader(int pipeSize) {
initPipe(pipeSize);
}
// 初始化“管道”:新建缓冲区大小
private void initPipe(int pipeSize) {
if (pipeSize <= 0) {
throw new IllegalArgumentException("Pipe size <= 0");
}
buffer = new char[pipeSize];
}
// 将“PipedReader”和“PipedWriter”绑定。
// 实际上,这里调用的是PipedWriter的connect()函数
public void connect(PipedWriter src) throws IOException {
src.connect(this);
}
// 接收int类型的数据b。
// 它只会在PipedWriter的write(int b)中会被调用
synchronized void receive(int c) throws IOException {
// 检查管道状态
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByWriter || closedByReader) {
throw new IOException("Pipe closed");
} else if (readSide != null && !readSide.isAlive()) {
throw new IOException("Read end dead");
}
// 获取“写入管道”的线程
writeSide = Thread.currentThread();
// 如果“管道中被读取的数据,等于写入管道的数据”时,
// 则每隔1000ms检查“管道状态”,并唤醒管道操作:若有“读取管道数据线程被阻塞”,则唤醒该线程。
while (in == out) {
if ((readSide != null) && !readSide.isAlive()) {
throw new IOException("Pipe broken");
}
/* full: kick any waiting readers */
notifyAll();
try {
wait(1000);
} catch (InterruptedException ex) {
throw new java.io.InterruptedIOException();
}
}
if (in < 0) {
in = 0;
out = 0;
}
buffer[in++] = (char) c;
if (in >= buffer.length) {
in = 0;
}
}
// 接收字符数组b。
synchronized void receive(char c[], int off, int len) throws IOException {
while (--len >= ) {
receive(c[off++]);
}
}
// 当PipedWriter被关闭时,被调用
synchronized void receivedLast() {
closedByWriter = true;
notifyAll();
}
// 从管道(的缓冲)中读取一个字符,并将其转换成int类型
public synchronized int read() throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByReader) {
throw new IOException("Pipe closed");
} else if (writeSide != null && !writeSide.isAlive()
&& !closedByWriter && (in < )) {
throw new IOException("Write end dead");
}
readSide = Thread.currentThread();
int trials = 2;
while (in < 0) {
if (closedByWriter) {
/* closed by writer, return EOF */
return -1;
}
if ((writeSide != null) && (!writeSide.isAlive()) && (--trials < )) {
throw new IOException("Pipe broken");
}
/* might be a writer waiting */
notifyAll();
try {
wait(1000);
} catch (InterruptedException ex) {
throw new java.io.InterruptedIOException();
}
}
int ret = buffer[out++];
if (out >= buffer.length) {
out = 0;
}
if (in == out) {
/* now empty */
in = -1;
}
return ret;
}
// 从管道(的缓冲)中读取数据,并将其存入到数组b中
public synchronized int read(char cbuf[], int off, int len) throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByReader) {
throw new IOException("Pipe closed");
} else if (writeSide != null && !writeSide.isAlive()
&& !closedByWriter && (in < 0)) {
throw new IOException("Write end dead");
}
if ((off < 0) || (off > cbuf.length) || (len < 0) ||
((off + len) > cbuf.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
/* possibly wait on the first character */
int c = read();
if (c < 0) {
return -1;
}
cbuf[off] = (char)c;
int rlen = 1;
while ((in >= 0) && (--len > 0)) {
cbuf[off + rlen] = buffer[out++];
rlen++;
if (out >= buffer.length) {
out = 0;
}
if (in == out) {
/* now empty */
in = -;
}
}
return rlen;
}
// 是否能从管道中读取下一个数据
public synchronized boolean ready() throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByReader) {
throw new IOException("Pipe closed");
} else if (writeSide != null && !writeSide.isAlive()
&& !closedByWriter && (in < )) {
throw new IOException("Write end dead");
}
if (in < 0) {
return false;
} else {
return true;
}
}
// 关闭PipedReader
public void close() throws IOException {
in = -;
closedByReader = true;
}
}
import java.io.IOException;
import java.io.PipedReader;
@SuppressWarnings("all")
/**
* 接收者线程
*/
public class Receiver extends Thread {
// 管道输入流对象。
// 它和“管道输出流(PipedWriter)”对象绑定,
// 从而可以接收“管道输出流”的数据,再让用户读取。
private PipedReader in = new PipedReader();
// 获得“管道输入流对象”
public PipedReader getReader(){
return in;
}
@Override
public void run(){
readMessageOnce() ;
//readMessageContinued() ;
}
// 从“管道输入流”中读取次数据
public void readMessageOnce(){
// 虽然buf的大小是2048个字符,但最多只会从“管道输入流”中读取1024个字符。
// 因为,“管道输入流”的缓冲区大小默认只有1024个字符。
char[] buf = new char[2048];
try {
int len = in.read(buf);
System.out.println(new String(buf,0,len));
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 从“管道输入流”读取>1024个字符时,就停止读取
public void readMessageContinued(){
int total=0;
while(true) {
char[] buf = new char[];
try {
int len = in.read(buf);
total += len;
System.out.println(new String(buf,,len));
// 若读取的字符总数>1024,则退出循环。
if (total > 1024)
break;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sender.java的代码如下:
import java.io.IOException;
import java.io.PipedWriter;
@SuppressWarnings("all")
/**
* 发送者线程
*/
public class Sender extends Thread {
// 管道输出流对象。
// 它和“管道输入流(PipedReader)”对象绑定,
// 从而可以将数据发送给“管道输入流”的数据,然后用户可以从“管道输入流”读取数据。
private PipedWriter out = new PipedWriter();
// 获得“管道输出流”对象
public PipedWriter getWriter(){
return out;
}
@Override
public void run(){
writeShortMessage();
//writeLongMessage();
}
// 向“管道输出流”中写入一则较简短的消息:"this is a short message"
private void writeShortMessage() {
String strInfo = "this is a short message" ;
try {
out.write(strInfo.toCharArray());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 向“管道输出流”中写入一则较长的消息
private void writeLongMessage() {
StringBuilder sb = new StringBuilder();
// 通过for循环写入1020个字符
for (int i=0; i<102; i++)
sb.append("0123456789");
// 再写入26个字符。
sb.append("abcdefghijklmnopqrstuvwxyz");
// str的总长度是1020+26=1046个字符
String str = sb.toString();
try {
// 将1046个字符写入到“管道输出流”中
out.write(str);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.IOException;
@SuppressWarnings("all")
/**
* 管道输入流和管道输出流的交互程序
*/
public class PipeTest {
public static void main(String[] args) {
Sender t1 = new Sender();
Receiver t2 = new Receiver();
PipedWriter out = t1.getWriter();
PipedReader in = t2.getReader();
try {
//管道连接。下面句话的本质是一样。
//out.connect(in);
in.connect(out);
/**
* Thread类的START方法:
* 使该线程开始执行;Java 虚拟机调用该线程的 run 方法。
* 结果是两个线程并发地运行;当前线程(从调用返回给 start 方法)和另一个线程(执行其 run 方法)。
* 多次启动一个线程是非法的。特别是当线程已经结束执行后,不能再重新启动。
*/
t.start();
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is a short message
public void write(char cbuf[]) throws IOException {
write(cbuf, 0, cbuf.length);
}
public void run(){
writeShortMessage();
//writeLongMessage();
}
public void run(){
//writeShortMessage();
writeLongMessage();
}
while (in == out) {
if ((readSide != null) && !readSide.isAlive()) {
throw new IOException("Pipe broken");
}
/* full: kick any waiting readers */
notifyAll();
try {
wait(1000);
} catch (InterruptedException ex) {
throw new java.io.InterruptedIOException();
}
}
public void run(){
readMessageOnce() ;
//readMessageContinued() ;
}
public void run(){
//readMessageOnce() ;
readMessageContinued() ;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有