练习 2015-08-15 管道流 用于线程之间交互数据

来源:互联网 发布:幼儿认字软件 编辑:程序博客网 时间:2024/05/19 08:38
package piped;


import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;


class ThreadA implements Runnable {
private PipedOutputStream out = new PipedOutputStream();

public PipedOutputStream getOut() {
return out;
}


public void run() {
try {
for (int i = 65; i < 65 + 26; i++) {
out.write(i);
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


class ThreadB implements Runnable{
private PipedInputStream in =null;

ThreadB(ThreadA a) throws Exception{
this.in = new PipedInputStream(a.getOut());
}

public void run() {
int len =-1;
try {
while((len = in.read()) != -1){
System.out.println((char)len);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}


//管道流
public class PipedDemo {
public static void main(String[] args) throws Exception {
ThreadA a = new ThreadA();
ThreadB b = new ThreadB(a);
new Thread(a).start();
new Thread(b).start();

}
}