package yn.ngems.cn;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class ThreadandSteam {//管道流
public static void main(String[] args) throws IOException {
SendThread send = new SendThread();
RecieveThread recieve = new RecieveThread();
send.getOutput().connect(recieve.getInput());
new Thread(send,"发送消息线程:").start();
new Thread(recieve,"接收消息线程:").start();
}
}
class SendThread implements Runnable{
private PipedOutputStream output;
public SendThread() {
this.output = new PipedOutputStream();
}
public void send() {
try {
for(int x = 0;x < 10;x ++) {
this.output.write(("【发送第" + x + "次消息】:" + (Thread.currentThread().getName() + "请登录地址:yn.ngems.cn\n")).getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
try {
this.output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
this.send();
}
public PipedOutputStream getOutput() {
return this.output;
}
}
class RecieveThread implements Runnable{
private PipedInputStream input;
public RecieveThread() {
this.input = new PipedInputStream();
}
public void recieve() {
try {
byte data [] = new byte [1024];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len = this.input.read(data)) != -1) {
baos.write(data,0,len);
}
System.out.println(Thread.currentThread().getName() + "接收消息:\n" + new String(baos.toByteArray()));
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
this.input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
this.recieve();
}
public PipedInputStream getInput() {
return this.input;
}
}
模拟管道流
猜你喜欢
转载自blog.csdn.net/qq_27347147/article/details/85084539
今日推荐
周排行