您的位置:首页 > 其它

线程之间通过管道通信

2017-07-18 20:28 411 查看
package newThread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

class ReaderThread extends Thread {
private PipedReader pr;
//用于包装管道流的BufferReader对象
private BufferedReader br;

public ReaderThread() {
super();
}

public ReaderThread(PipedReader pr) {
super();
this.pr = pr;
this.br=new BufferedReader(pr);//将管道的字符流输出到buf缓存中
}

@Override
public void run() {
String buf=null;
try {
//逐行读取管道输入流中的内容
while((buf=br.readLine())!=null) {
System.out.println(buf);
}
}catch(IOException ex){
ex.printStackTrace();
}finally {
try {
if(br!=null)br.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}

}
class WriterThread extends Thread{
String[] books=new String[] {
"struts2权威指南",
"ROR敏捷开发指南",
"基于J2EE的Ajax宝典",
"轻量级J2ee企业应用指南"
};
private PipedWriter pw;

public WriterThread() {
super();
}

public WriterThread(PipedWriter pw) {
super();
this.pw = pw;
}

@Override
public void run() {
try {
for(int i=0;i<100;i++) {
pw.write(books[i%4]+"\n");//向管道输出字符流
}
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(pw!=null)pw.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class PipedCommunicationTest{
public static void main(String[] args) {
PipedWriter pw=null;
PipedReader pr=null;
try {//分别创建两个独立的管道输出流、输入流
pw=new PipedWriter();
pr=new PipedReader();
//连接管道输出流输入流
pw.connect(pr);
//将链接好的管道流分别传入两个线程
//就可以让两个线程通过管道流进行通信
new WriterThread(pw).start();
new ReaderThread(pr).start();
}catch (Exception e) {
e.printStackTrace();
}
}
}


运行结果:



特别说明一般线程不用管道通信,因为线程同属于一个进程,它们可以共享进程的资源
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程 通信 管道