验证中...
本周日(5月27日)码云企业技术分享会【微服务】专场将与你相约上海。阿里、华为、ThoughtWorks的技术大咖齐聚,等你来撩!
gistfile1.txt
原始数据 复制代码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 线程之间的通讯(通过管道流实现线程之间的通讯)
* @author Administrator
*
*/
public class Test4 {
public static void main(String[] args) throws IOException {
//读入流
PipedInputStream pins =new PipedInputStream();
//输出流
PipedOutputStream pos =new PipedOutputStream();
//输入流和输出流建立连接
pos.connect(pins);
AThread a =new AThread(new BufferedWriter(new OutputStreamWriter(pos)));
BThread b =new BThread(new BufferedReader (new InputStreamReader(pins)));
a.start();
b.start();
}
}
//发送者
class AThread extends Thread{
BufferedWriter bw;
public AThread(BufferedWriter bw){
this.bw=bw;
}
@Override
public void run() {
try {
bw.write("你好前任,好你");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(bw!=null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
bw=null;
}
}
}
}
//接受者
class BThread extends Thread{
BufferedReader br;
public BThread(BufferedReader br){
this.br=br;
}
@Override
public void run() {
try {
String str = br.readLine();
System.out.println("我是接受者:"+str);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
br=null;
}
}
}
}

评论列表( 0 )

你可以在登录后,发表评论

9_float_left_people 9_float_left_close