多线程之间的通信~~~管道通道
❀管道流:主要用于线程之间的通信,传输的媒介是内存!传输的媒介是内存,传输的媒介是内存,传输的媒介是内存
其实就跟咱之前学得io 流操作一致,只是在io 流 基础上结合了线程(任务)的知识!
(ps: 线程之间的通信模式:生产者消费者模式通过“信息通道”------内存缓存区)
(1)字节流、字符流的管道通道
字节流:PipedInputStream,PipedOutputStream
字符流:PipedRead、PipedWriter
(2) 将输入流和输出流进行连接,用connect() 方法,方便在多个线程中传输数据。
writer.connect(reader); //等价于 reader.connect(writer); 因为你连我,就是我连你呀
(3) 连接后,两个线程就可以进行通信了。相当于通过写入通道写入的资源 流通到了(connect) 读取通道里。
//发送消息、接收消息
new Thread(new SendMessegeTask(pipOutStream)).start();
new Thread(new AcceptMessegeTask(pipedInStream)).start();
❀案例代码:
❀ 发送消息 class SendMessegeTask
package ChatWithSelf;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Scanner;
/**
* 发送消息
* @author Huangyujun
*
*/
public class SendMessegeTask implements Runnable {
private PipedOutputStream pipOutStream;
public SendMessegeTask(PipedOutputStream pipOutStream) {
this.pipOutStream = pipOutStream;
}
Scanner scanner = new Scanner(System.in);
@Override
public void run() {
while(true) {
// 不断地写入
System.out.println("请输入要发生的内容:");
String content = scanner.next();
byte[] byteContent = content.getBytes();
// new byte[1024];
// byteContent = content.getBytes();
try {
pipOutStream.write(byteContent, 0, byteContent.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
❀ 接收消息 class AcceptMessegeTask
package ChatWithSelf;
import java.io.IOException;
import java.io.PipedInputStream;
/**
* 接收消息
* @author Huangyujun
*
*/
public class AcceptMessegeTask implements Runnable{
private PipedInputStream pipedInStream;
public AcceptMessegeTask(PipedInputStream pipedInStream) {
this.pipedInStream = pipedInStream;
}
@Override
public void run() {
while(true) {
// 不断地读取,前面接收的是字节数组的内容
byte[] buffer = new byte[1024];
int read = -1;
try {
while((read = pipedInStream.read(buffer)) != -1) {
//打印到公屏上
System.out.println(new String(buffer));
//为下一次做空间准备
buffer = new byte[1024];
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
❀ 管道通信 class Piped
package ChatWithSelf;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Scanner;
/**
* 管道通信
* @author Huangyujun
*
*/
public class Piped {
public static void main(String[] args) throws IOException {
PipedInputStream pipedInStream = new PipedInputStream();
PipedOutputStream pipOutStream = new PipedOutputStream();
//联通
// pipOutStream.connect(pipedInStream);
pipedInStream.connect(pipOutStream);
//发送消息、接收消息
new Thread(new SendMessegeTask(pipOutStream)).start();
new Thread(new AcceptMessegeTask(pipedInStream)).start();
}
}
参考:老九学堂~《java线上训练营~网络编程~多线程之间的另外一种通信方式管道通道》
作者:一乐乐