?? pipedcommunicationtest.java
字號:
import java.io.*;
/**
* Description:
* <br/>Copyright (C), 2008-2010, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
class ReaderThread extends Thread
{
private PipedReader pr;
//用于包裝管道流的BufferReader對象
private BufferedReader br;
public ReaderThread(){}
public ReaderThread(PipedReader pr)
{
this.pr = pr;
this.br = new BufferedReader(pr);
}
public void run()
{
String buf = null;
try
{
//逐行讀取管道輸入流中的內(nèi)容
while ((buf = br.readLine()) != null)
{
System.out.println(buf);
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
//使用finally塊來關(guān)閉輸入流
finally
{
try
{
if (br != null)
{
br.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
class WriterThread extends Thread
{
String[] books = new String[]
{
"Struts2權(quán)威指南",
"ROR敏捷開發(fā)指南",
"基于J2EE的Ajax寶典",
"輕量級J2EE企業(yè)應(yīng)用指南"
};
private PipedWriter pw;
public WriterThread(){}
public WriterThread(PipedWriter pw)
{
this.pw = pw;
}
public void run()
{
try
{
//循環(huán)100次,向管道輸出流中寫入100個字符串
for (int i = 0; i < 100 ; i++)
{
pw.write(books[i % 4] + "\n");
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
//使用finally塊來關(guān)閉管道輸出流
finally
{
try
{
if (pw != null)
{
pw.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
public class PipedCommunicationTest
{
public static void main(String[] args)
{
PipedWriter pw = null;
PipedReader pr = null;
try
{
//分別創(chuàng)建兩個獨(dú)立的管道輸出流、輸入流
pw = new PipedWriter();
pr = new PipedReader();
//連接管道輸出流、出入流
pw.connect(pr);
//將連接好的管道流分別傳入2個線程,
//就可以讓兩個線程通過管道流進(jìn)行通信
new WriterThread(pw).start();
new ReaderThread(pr).start();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -