在一个jvm中的不同线程之间可以通过管道进行通信,一个线程持有PipeOutputStream向管道中写数据,一个线程持有PipeInputStream从管道中读取数据。

输出线程Writer,持有PipedOutputStream
/*** 输出线程*/public class Writer implements Runnable{private PipedOutputStream pipedOutputStream;public Writer(PipedOutputStream pipedOutputStream){this.pipedOutputStream = pipedOutputStream;}@Overridepublic void run() {if(pipedOutputStream!=null){//读取控制台信息BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));String content = null;try {content = reader.readLine();String msg = Thread.currentThread().getName()+":"+content;pipedOutputStream.write(msg.getBytes(StandardCharsets.UTF_8));} catch (IOException e) {e.printStackTrace();}}//关闭输出流try {pipedOutputStream.close();}catch (Exception e){e.printStackTrace();}}}
输入线程Reader,持有PipedInputStream
/*** reader线程从输入管道中读取数据*/public class Reader implements Runnable{private PipedInputStream pipedInputStream;public Reader(PipedInputStream pipedInputStream) {this.pipedInputStream = pipedInputStream;}@Overridepublic void run() {if (pipedInputStream != null) {String collect = new BufferedReader(new InputStreamReader(pipedInputStream)).lines().collect(Collectors.joining("\n"));System.out.println(Thread.currentThread().getName()+":" +collect);}try {pipedInputStream.close();} catch (IOException e) {e.printStackTrace();}}}
Main线程
关键:
1、将输入管道和输出管道连接
2、向不同的线程提供不同的管道
/*** 线程间通过管道通信*/public class Main {public static void main(String[] args) throws IOException {//输入管道PipedInputStream pipedInputStream = new PipedInputStream();//输出管道PipedOutputStream pipedOutputStream = new PipedOutputStream();//将输出管道和输入管道连接,数据是从输出管道传到输入管道pipedOutputStream.connect(pipedInputStream);//reader线程持有输入管道new Thread(new Reader(pipedInputStream),"reader").start();//writer线程持有输出管道new Thread(new Writer(pipedOutputStream),"writer").start();}}
vip算法班永久学习班: 800元/人
周一、周三、周五:8:30-9:30,周六、周日:10:30-11:30
报名方式:通过公众号导航栏的刷题群即可联系到我的微信号
算法班详情如下:
奔跑的小梁,公众号:梁霖编程工具库算法训练营快来参加吧~
vip算法班同学的学习后的总结分享,不得不说,确实比我当年厉害!!!

文章转载自梁霖编程工具库,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




