黑马程序员技术交流社区
标题:
对视频教程中管道流代码的一点小小的优化
[打印本页]
作者:
王金科
时间:
2012-8-20 18:26
标题:
对视频教程中管道流代码的一点小小的优化
教程中原代码:
package cn.study.file;
import java.io.*;
public class PipedStreamDemo1
{
public static void main(String[] args) throws IOException
{
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
in.connect(out);
Read r = new Read(in);
Write w = new Write(out);
new Thread(w).start();
new Thread(r).start();
}
}
class Read implements Runnable
{
private PipedInputStream in;
Read(PipedInputStream in)
{
this.in = in;
}
public void run()
{
try
{
byte[] buf = new byte[1024];
System.out.println("读取前,没有数据,阻塞...");
int len = in.read(buf);
System.out.println("读到数据了");
String s = new String(buf,0,len);
System.out.println(s);
in.close();
}
catch (IOException e)
{
throw new RuntimeException("管道读取流失败");
}
}
}
class Write implements Runnable
{
private PipedOutputStream out;
Write(PipedOutputStream out)
{
this.out = out;
}
public void run()
{
try
{
System.out.println("开始写入数据,等待6秒...");
Thread.sleep(6000);
out.write("pipde 来了".getBytes());
out.close();
}
catch (Exception e)
{
throw new RuntimeException("管道输出流失败");
}
}
}
复制代码
我优化后的代码
package cn.study.file;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
final PipedInputStream pis = new PipedInputStream();
final PipedOutputStream pos = new PipedOutputStream();
Thread read = new Thread(){
public void run(){
try {
byte[] buf = new byte[1024];
System.out.println("读取前,没有数据,等待...");
int len = pis.read(buf);
System.out.println("读到数据,打印数据...");
String str = new String(buf,0,len);
System.out.println(str);
pis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Runnable write = new Runnable(){
public void run(){
try {
System.out.println("开始写入数据,等待6秒后...");
Thread.sleep(6000);
pos.write("piped lai la".getBytes());
pos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
pis.connect(pos);
read.start();
new Thread(write).start();
}
}
复制代码
大家帮我看看这样会不会有什么缺陷
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2