管道流
管道流主要可以进行两个线程之间的通信。
PipedOutputStream 管道输出流
PipedInputStream 管道输入流
send类:负责消息发送
package wgl.message;
import java.io.IOException;
import java.io.PipedOutputStream;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Send implements Runnable{
private String message;
private int counter ;
private PipedOutputStream output ;
public Send(PipedOutputStream out ,String message){
output = out;
this.message = message;
this.counter = 1;
}
@Override
public void run() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if(counter==15){
}
sendMessage("第"+(counter++)+"次:"+message);
}
},new Date(), 2000);
}
public void sendMessage(String message){
try {
System.out.println("发送的内容:"+message);
output.write(message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public String getMessage() {
return message;
}
public PipedOutputStream getOutput() {
return output;
}
}
package wgl.message;
import java.io.IOException;
import java.io.PipedInputStream;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Recieve implements
Runnable{
private PipedInputStream in;
public Recieve(PipedInputStream in){
this.in = in;
}
@Override
public void run() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
recieved();
}
},new Date(), 200);
}
public void recieved(){
byte[] b = new byte[1000];
int len = 0;
try {
len = this.in.read(b);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("接受的内容:"+new String(b, 0, len));
}
public PipedInputStream getIn() {
return in;
}
}
Connect :测试类 测试两个线程通信
package wgl.message;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Connect {
public static void main(String[] args) throws IOException{
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream();
final Send send = new Send(out,"你好!");
final Recieve recieve = new Recieve(in);
send.getOutput().connect(recieve.getIn());
Thread t1 = new Thread(send);
Thread t2 = new Thread(recieve);
t1.start();
t2.start();
}
}
【运行结果】:
发送的内容:第1次:你好!
接受的内容:第1次:你好!
发送的内容:第2次:你好!
接受的内容:第2次:你好!
发送的内容:第3次:你好!
接受的内容:第3次:你好!
发送的内容:第4次:你好!
接受的内容:第4次:你好!
......