Thread详解10:用管道进行线程间通信
2016-03-30 18:41
513 查看
1 字节流管道
通常,数据由某个线程从 PipedInputStream 对象读取,并由其他线程将其写入到相应的 PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可在缓冲区限定的范围内将读操作和写操作分离开。 如果向连接管道输出流提供数据字节的线程不再存在,则认为该管道已损坏。1.1 PipedInputStream
1.2 PipedOutputStream
1.3 使用字节流管道进行线程间的通信
WriteData.java
package pipe; import java.io.IOException; import java.io.PipedOutputStream; public class WriteData extends Thread { private PipedOutputStream pipedOS; private String data; public WriteData(PipedOutputStream pipedOS, String data) { super("Writer"); this.pipedOS = pipedOS; this.data = data; } @Override public void run() { super.run(); try { String tmp; for (int i = 0; i < 6; i++) { tmp = data + i + " "; System.out.println(Thread.currentThread().getName() + " writed " + tmp + " into the pipe."); pipedOS.write(tmp.getBytes()); } pipedOS.flush(); pipedOS.close(); } catch (IOException e) { e.printStackTrace(); } } }
ReadData.java
package pipe; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; public class ReadData extends Thread { private PipedInputStream pipedIS; public ReadData(PipedInputStream pipedIS) { super("Reader"); this.pipedIS = pipedIS; } @Override public void run() { super.run(); try { System.out.println(Thread.currentThread().getName() + " begined reading the data from the pipe."); byte[] bytes = new byte[20]; int readLen = -1; readLen = pipedIS.read(bytes); while (readLen != -1) { String s = new String(bytes, 0, readLen); System.out.println(s); try { readLen = pipedIS.read(bytes); } catch (IOException e) { e.printStackTrace(); } } System.out.println(); pipedIS.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { PipedInputStream pipedInputStream = new PipedInputStream(); PipedOutputStream pipedOutputStream = new PipedOutputStream(); try { pipedInputStream.connect(pipedOutputStream); } catch (IOException e) { e.printStackTrace(); } WriteData writeData = new WriteData(pipedOutputStream, "ABC"); ReadData readData = new ReadData(pipedInputStream); writeData.start(); readData.start(); } }
输出
Reader begined reading the data from the pipe. Writer writed ABC0 into the pipe. Writer writed ABC1 into the pipe. Writer writed ABC2 into the pipe. Writer writed ABC3 into the pipe. Writer writed ABC4 into the pipe. Writer writed ABC5 into the pipe. ABC0 ABC1 ABC2 ABC3 ABC4 ABC5
2 字符流通道
2.1 PipedReader
2.2 PipedWriter
由于管道通信的原理是一样的,不过一个是处理字节流,一个是处理字符流,区别不大,所以这里代码就不再编写了。
相关文章推荐
- Shell 管道及执行顺序分析
- Windows Powershell 管道和重定向
- PHP多线程编程之管道通信实例分析
- Go语言的管道Channel用法实例
- Python实现处理管道的方法
- Python中使用PIPE操作Linux管道
- Python多线程编程(八):使用Event实现线程间通信
- go语言通过管道连接两个命令行进程的方法
- python中管道用法入门实例
- Kafka剖析(一):Kafka背景及架构介绍
- linux之sed用法
- 进程间通信之管道与有名管道
- asp.net 页面生命周期
- lsof 查看进程打开那些文件 和 查看文件给那个进程使用
- IIS7.0 报错 检测到在集成的托管管道模式下不适用的 ASP.NET 设置
- linux命令之玩转xargs
- bash字符串处理
- 无名管道pipe 有名管道fifo
- 管道
- 服务器serverbuffergcc数据结构Linux进程通信:命名管道FIFO小结