package io;
import java.io.*;
/*
* 修改日期:2020/04/05
* 修改人:牟松
* 管道流(字符流)PipedReader和PipedWriter基本操作练习
* 参考链接:https://blog.csdn.net/sk199048/article/details/51260757
*/
* 修改日期:2020/04/05
* 修改人:牟松
* 管道流(字符流)PipedReader和PipedWriter基本操作练习
* 参考链接:https://blog.csdn.net/sk199048/article/details/51260757
*/
class Producer extends Thread {
private PipedWriter writer = new PipedWriter();
public Producer(PipedWriter writer) {
this.writer = writer;
}
public Producer(PipedWriter writer) {
this.writer = writer;
}
@Override
public void run() {
try {
StringBuilder sb = new StringBuilder();
sb.append("Hello World!");
writer.write(sb.toString());
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void run() {
try {
StringBuilder sb = new StringBuilder();
sb.append("Hello World!");
writer.write(sb.toString());
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Consumer extends Thread{
private PipedReader reader = new PipedReader();
public Consumer(PipedReader reader) {
this.reader = reader;
}
this.reader = reader;
}
@Override
public void run() {
try {
char [] cbuf = new char[20];
reader.read(cbuf, 0, cbuf.length);
System.out.println("管道流中的数据为: " + new String(cbuf));
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void run() {
try {
char [] cbuf = new char[20];
reader.read(cbuf, 0, cbuf.length);
System.out.println("管道流中的数据为: " + new String(cbuf));
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ceshi {
public static void main(String[] args)
{
/**
* 线程间通过管道流通信的步骤为
* 1 建立输入输出流
* 2 绑定输入输出流
* 3 Writer写
* 4 Reader读
*/
public static void main(String[] args)
{
/**
* 线程间通过管道流通信的步骤为
* 1 建立输入输出流
* 2 绑定输入输出流
* 3 Writer写
* 4 Reader读
*/
PipedReader reader = new PipedReader();
PipedWriter writer = new PipedWriter();
Producer producer = new Producer(writer);
Consumer consumer = new Consumer(reader);
PipedWriter writer = new PipedWriter();
Producer producer = new Producer(writer);
Consumer consumer = new Consumer(reader);
try {
writer.connect(reader);
producer.start();
consumer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
writer.connect(reader);
producer.start();
consumer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}