通过字节流实现线程通信

本文详细介绍了一种利用PipedInputStream和PipedOutputStream实现Java线程间通信的方法。通过具体的代码示例,演示了如何创建读写线程,并通过管道流进行数据交换,实现了线程间的有效通信。
摘要由CSDN通过智能技术生成
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,

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值