首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

(IO)管道源的应用-使用多线程技术

2013-11-21 
(IO)管道流的应用---使用多线程技术管道流---输入流与输出流结合A线程负责往管道中写数据B线程负责从管道

(IO)管道流的应用---使用多线程技术

管道流---输入流与输出流结合

A线程负责往管道中写数据

B线程负责从管道中读数据

?

package com.gc.stream;import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutputStream;/** * 管道流 *将输入流与输出流进行结合 *A线程负责写,B线程负责读 *必须用多线程,一个线程用来写,另一个线程用来读 *  * @author Administrator * */public class PipedStreamDemo {public static void main(String[] args) throws IOException {//创建输出管道流---将数据写入到管道中PipedOutputStream pipeOut = new PipedOutputStream();//创建输入管道流---从管道中读数据PipedInputStream pipeIn = new PipedInputStream();//使用管道将输出流与输入流进行连接pipeIn.connect(pipeOut);//负责写的线程new Thread(new Outter(pipeOut)).start();//负责读的线程new Thread(new Inner(pipeIn)).start();}}/** * 负责读取数据,往管道中写的线程 * */class Outter implements Runnable {private PipedOutputStream out;public Outter(PipedOutputStream out) {this.out = out;}@Overridepublic void run() {String data = "有点郁闷";try {out.write(data.getBytes());out.flush();} catch (IOException e) {e.printStackTrace();}}}/** * 负责从管道中读取数据数据的线程 * */class Inner implements Runnable {private PipedInputStream in;public Inner(PipedInputStream in) {this.in = in;}@Overridepublic void run() {byte[] buf = new byte[1024];try {int len = in.read(buf);String data = new String(buf,0,len);System.out.println("从管道流中读取到数据:"+data);} catch (IOException e) {e.printStackTrace();}}}

?

热点排行