線程流,顧名思義就是在線程之間傳輸數據的流。主要用途自然就是用於線程之間通訊。
線程流必須輸入輸出一起使用只使用一個會拋出 java.io.IOException: Pipe not connected 而且也不能一個對應多個 只能一對一,一對多會拋出 java.io.IOException: Already connected ;
例:
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Tests {
/**
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
PipedOutputStream os = new PipedOutputStream();
// os.write("".getBytes());//解除註釋,會拋出 java.io.IOException: Pipe not connected
PipedInputStream in = new PipedInputStream(os);
//解除下面兩行註釋會拋出 java.io.IOException: Already connected
// PipedInputStream in1 = new PipedInputStream(os);
// new Tests().new B(in1).start();
new Tests().new A(os).start();
new Tests().new B(in).start();
/**
* 除了可以在實例化這兩個對象時將兩個流對象綁定 ,
* 還可以通過調用 in.connect(PipedOutputStream src);方法來連接兩個流
* 兩個流只需要連接一次,不限制順序,可以in.connect(os),也可以相反
*/
}
class A extends Thread{
PipedOutputStream os= null;
public A(PipedOutputStream os) {
super("A");
this.os = os;
}
public void run() {
while(true) {
try {
os.write("0123456789".getBytes());
os.flush();
System.err.println(this.getName()+" : "+"0123456789");
Thread.sleep(1000);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class B extends Thread{
PipedInputStream in = null;
public B(PipedInputStream in) {
super("B");
this.in = in;
}
public void run() {
byte[] b = new byte[10];
int len = 0;
try {
while((len=in.read(b))>0) {
System.out.println(this.getName()+" : "+new String(b,0,len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ps:線程間通訊不僅僅只有這一種方式,而且實際開發中,很少會用到這種方式,僅作爲一種瞭解方式