管道通信原理
来源:互联网 发布:程序员和黑客谁厉害 编辑:程序博客网 时间:2024/05/21 12:06
PipedInputStream类与PipedOutputStream类用于在应用程序中创建管道通信.一个PipedInputStream实例对象必须和一个PipedOutputStream实例对象进行连接而产生一个通信管道.PipedOutputStream可以向管道中写入数据,PipedIntputStream可以读取PipedOutputStream向管道中写入的数据.这两个类主要用来完成线程之间的通信.一个线程的PipedInputStream对象能够从另外一个线程的PipedOutputStream对象中读取数据.
PipedInputStream与PipedOutputStream类的编程实例(两个线程间进行通信的实例程序)
发送者
import java.io.IOException;
import java.io.PipedOutputStream;
import java.util.Scanner;
public class Sender extends Thread {
private PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream getOut(){
return out;
}
public void run(){
System.out.println("请输入您要发送的内容:");
Scanner sc = new Scanner(System.in);
String comtent = sc.next();
//String strInfo = new String("Hello,rec");
try {
//out.write(strInfo.getBytes());
out.write(comtent.getBytes());
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//System.out.println(e);
}
}
}
接收者
import java.io.IOException;
import java.io.PipedInputStream;
public class Receiver extends Thread{
private PipedInputStream in = new PipedInputStream();
public PipedInputStream getIn(){
return in;
}
public void run(){
byte [] buf = new byte[1024];
try {
int len = in.read(buf);
System.out.println("the following message comes form sender:/n"
+new String(buf,0,len));
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//System.out.println(e);
}
}
}
测试程序
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Sender send = new Sender();
Receiver receiv = new Receiver();
PipedOutputStream out = send.getOut();
PipedInputStream in = receiv.getIn();
try {
out.connect(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
send.start();
receiv.start();
}
}
- 管道通信原理
- linux管道通信原理
- 管道通信
- 管道通信
- 管道通信
- 管道通信
- 管道通信
- 管道通信
- 管道通信
- 管道通信
- 管道通信
- 管道通信 .
- 管道通信
- 管道通信
- 管道通信
- 管道通信
- 管道通信
- 管道通信
- 从index.jsp跳转到showMain.jsp
- android 获取系统的参数(如音量大小,背光,网络类型等)
- ubuntu10.10 的ping localhost问题
- pv210+Froyo
- WAS JDK 1.5 存在堆碎片吗?
- 管道通信原理
- 豆瓣在推荐领域的实践和思考
- JavaScript窗口功能指南之打开一个新窗口
- HTML表格中绑定显示XML文档内容的简单实例
- 豆瓣数据存储实践
- 圣天诺SuperPro狗模拟视频语音教程
- wireshark抓http包时的过滤
- GetWindowRect和GetClientRect
- window.open参数完全手册