成都创建公司网站,wordpress的多说美化,wordpress去掉,专做水果店加盟的网站今天看了下关于管道的通信#xff0c;Java中的管道只能在同一进程的不同线程间通信。今天测试两个线程进行通信发现报错。下面是我测试的代码。package com.wpl.testIO;import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutputStream;public …今天看了下关于管道的通信Java中的管道只能在同一进程的不同线程间通信。今天测试两个线程进行通信发现报错。下面是我测试的代码。package com.wpl.testIO;import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutputStream;public class IoOne {SuppressWarnings(resource)public static void main(String[] args) throws IOException {final PipedOutputStream outputStreamnew PipedOutputStream();final PipedInputStream inputStreamnew PipedInputStream(outputStream);Thread t1new Thread(new Runnable() {Overridepublic void run() {try {outputStream.write(Hello world.getBytes());//outputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});Thread t2new Thread(new Runnable() {Overridepublic void run() {try {int countinputStream.read();while(count!-1outputStream!null){System.out.print((char) count);countinputStream.read();}//inputStream.close();} catch (IOException e) {e.printStackTrace();}}});t1.start();t2.start();}}报错的图片如下。值能够读出来但是最后还是会报错不知道为何往上看了很多解决办法也没有用同时我的输入和输出并没有显示的关闭而是使用jdk1.7中的try-resources代替显示地调用close方法的方式。后来发现问题就出在这里将代码简单改写下就没有报错了。package com.wpl.testIO;import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutputStream;public class IoOne {public static void main(String[] args) throws IOException {final PipedOutputStream outputStreamnew PipedOutputStream();final PipedInputStream inputStreamnew PipedInputStream(outputStream);Thread t1new Thread(new Runnable() {Overridepublic void run() {try {outputStream.write(Hello world.getBytes());outputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});Thread t2new Thread(new Runnable() {Overridepublic void run() {try {int countinputStream.read();while(count!-1outputStream!null){System.out.print((char) count);countinputStream.read();}inputStream.close();} catch (IOException e) {e.printStackTrace();}}});t1.start();t2.start();}}其实还是资源没有关闭的问题下次应该注意。标签