管道流----基于线程通信
文章目录
管道流----基于线程通信前言案例演示运行结果总结
前言
管道流的主要作用是进行线程之间的通信。要实现线程通信,需要用到PipedInputStream、PipedOutputStream管道输入流和管道输出流两个类,它们都是字节流操作类,为InputStream和OutputStream的子类。
通过PipedOutputStream类的connect(PipedInputStream snk)进行两个线程通信类的连接,参数为线程通信接受类的管道输入流实例。
案例演示
package chapter_twelve
;
import java
.io
.IOException
;
import java
.io
.PipedInputStream
;
import java
.io
.PipedOutputStream
;
class Send implements Runnable{
private PipedOutputStream pipedOutputStream
;
public Send() {
this.pipedOutputStream
= new PipedOutputStream();
}
@Override
public void run() {
String string
= "Hello World!!!";
byte[] bytes
= string
.getBytes();
try {
this.pipedOutputStream
.write(bytes
);
this.pipedOutputStream
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
}
public PipedOutputStream
getPipedOutputStream() {
return pipedOutputStream
;
}
}
class Receive implements Runnable{
private PipedInputStream pipedInputStream
;
public Receive() {
this.pipedInputStream
= new PipedInputStream();
}
@Override
public void run() {
byte[] bytes
= new byte[1024];
try {
int len
= this.pipedInputStream
.read(bytes
);
this.pipedInputStream
.close();
System
.out
.println(new String(bytes
,0,len
));
} catch (IOException e
) {
e
.printStackTrace();
}
}
public PipedInputStream
getPipedInputStream() {
return pipedInputStream
;
}
}
public class PipedDemo {
public static void main(String
[] args
) throws Exception
{
Send send
= new Send();
Receive receive
= new Receive();
send
.getPipedOutputStream().connect(receive
.getPipedInputStream());
new Thread(send
).start();
new Thread(receive
).start();
}
}
运行结果
Hello World
!!!
总结
管道流在线程通信之间的应用比较广泛,也是对字节流操作的类。需要注意的是,若线程接受类未接收到管道输出流的传送数据,会等待管道输出流输出数据,所以小伙伴们不必担心 接受类先执行的问题,哈哈,这也是我之前的疑虑,如果有看法不同的大神,欢迎指教,共同进步!!!