package com.freeflying.thread.communication;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 通过字节流实现线程间通信
* @ClassName: CommunicationByPiped
* @Description:
* @author freeflying
* @date 2018年7月24日
*/
public class CommunicationByPiped {
public static void main(String[] args) {
try {
CommunicationByPipedWriteEx writeEx=new CommunicationByPipedWriteEx();
CommunicationByPipedReadEx readEx=new CommunicationByPipedReadEx();
PipedInputStream input=new PipedInputStream();
PipedOutputStream out=new PipedOutputStream();
out.connect(input);//让输入和输出流之间产生通信
CommunicationByPipedWriteThread writeThread=new CommunicationByPipedWriteThread(writeEx, out);
writeThread.start();
Thread.sleep(2000);
CommunicationByPipedReadThread readThread=new CommunicationByPipedReadThread(readEx, input);
readThread.start();
} catch (Exception e) {
}
}
}
class CommunicationByPipedWriteEx{
public void writeData(PipedOutputStream out) {
try {
System.out.println("begin write:");
for (int i = 0; i < 30; i++) {
String outData=i+",";
out.write(outData.getBytes());
System.out.print(outData);
}
System.out.println();
out.close();
} catch (Exception e) {
}
}
}
class CommunicationByPipedReadEx{
public void readData(PipedInputStream input) {
try {
System.out.println("begin read:");
byte[] byteArray=new byte[20];
int readLength=input.read(byteArray);
while(readLength!=-1) {
String inputData=new String(byteArray, 0, readLength);
System.out.print(inputData);
readLength=input.read(byteArray);
}
System.out.println();
input.close();
} catch (Exception e) {
}
}
}
class CommunicationByPipedWriteThread extends Thread{
private CommunicationByPipedWriteEx writeEx;
private PipedOutputStream out;
public CommunicationByPipedWriteThread(CommunicationByPipedWriteEx writeEx,PipedOutputStream out) {
this.writeEx=writeEx;
this.out=out;
}
@Override
public void run() {
writeEx.writeData(out);
}
}
class CommunicationByPipedReadThread extends Thread{
private CommunicationByPipedReadEx readEx;
private PipedInputStream input;
public CommunicationByPipedReadThread(CommunicationByPipedReadEx readEx,PipedInputStream input) {
this.readEx=readEx;
this.input=input;
}
@Override
public void run() {
readEx.readData(input);
}
}
结果:
begin write:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,
begin read:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,