JAVA_线程间流的通信

package com.kk.review;

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

public class PipedStream {
public static void main(String[] args) {
try{
PipedInputStream pis=new PipedInputStream();
PipedOutputStream pos=new PipedOutputStream();
pis.connect(pos);
new Producer(pos).start();
new Consumer(pis).start();
}catch(IOException ioe){
ioe.printStackTrace();
}

}
}

class Producer extends Thread {
PipedOutputStream pos;

public Producer(PipedOutputStream pos) {
this.pos = pos;
}

public void run(){
try{
pos.write("hello".getBytes());
pos.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}

class Consumer extends Thread{
PipedInputStream pis;
public Consumer(PipedInputStream pis) {
this.pis=pis;
}
public void run(){
try{
byte []buf=new byte[100];
int len=pis.read(buf);
String str=new String(buf,0,len);
System.out.println(str);
pis.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}



你可能感兴趣的:(java)