温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java 多线程使用PipedOutStream和PipedInputStream

发布时间:2020-08-07 18:20:15 来源:ITPUB博客 阅读:142 作者:hgs19921112 栏目:编程语言
package test;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipeTest {
public static void main(String[] args) throws Exception {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
//链接
pis.connect(pos);
//写线程
InThread it = new InThread(pos,pis);
//读线程
OutThread ot = new OutThread(pos,pis);
it.start();
ot.start();
Thread.sleep(1000);
}
}
class InThread extends Thread{
PipedOutputStream pos = null;
PipedInputStream pis = null ;
InThread(PipedOutputStream pos,PipedInputStream pis ){
this.pos = pos;
this.pis = pis;
}
public void run() {
try {
//写入数据
byte[] b = new String("this is a test !").getBytes();
pos.write(b);
//关闭链接,此处必须关闭,不然会包异常  
pos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class OutThread extends Thread{
PipedInputStream pis = null ;
PipedOutputStream pos = null;
OutThread(PipedOutputStream pos,PipedInputStream pis){
this.pis = pis;
this.pos = pos;
}
public void run() {
//读取数据
String m = "";
byte[] b = new byte[1024];
try {
int len ;
len = pis.read(b);
m = m+ new String(b);
while(len!=-1) {
len = pis.read(b); 
m = m+ new String(b);
}
//关闭资源
pis.close();
System.out.println(m);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI