写一个管道过滤器四个过滤器多线程的java代码
时间: 2023-10-18 15:18:44 浏览: 101
以下是一个简单的Java多线程管道过滤器代码示例,其中包含四个过滤器:
```java
import java.io.*;
public class PipelineFilterDemo {
public static void main(String[] args) {
try {
// 创建管道输入流和输出流
PipedInputStream inputStream = new PipedInputStream();
PipedOutputStream outputStream = new PipedOutputStream();
// 创建四个过滤器线程
Thread filter1 = new Filter1(inputStream);
Thread filter2 = new Filter2(new PipedInputStream(outputStream));
Thread filter3 = new Filter3(new PipedInputStream(outputStream));
Thread filter4 = new Filter4(new PipedInputStream(outputStream));
// 将管道输入流和输出流连接起来
inputStream.connect(outputStream);
// 启动过滤器线程
filter1.start();
filter2.start();
filter3.start();
filter4.start();
// 写入数据到管道输出流
String data = "Hello, World!";
outputStream.write(data.getBytes());
// 等待所有过滤器线程执行完成
filter1.join();
filter2.join();
filter3.join();
filter4.join();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
// 过滤器1
class Filter1 extends Thread {
private final InputStream inputStream;
Filter1(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
try {
int data = inputStream.read();
System.out.println("Filter1: " + (char) data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 过滤器2
class Filter2 extends Thread {
private final InputStream inputStream;
Filter2(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
try {
int data = inputStream.read();
System.out.println("Filter2: " + (char) (data + 1));
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 过滤器3
class Filter3 extends Thread {
private final InputStream inputStream;
Filter3(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
try {
int data = inputStream.read();
System.out.println("Filter3: " + (char) (data + 2));
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 过滤器4
class Filter4 extends Thread {
private final InputStream inputStream;
Filter4(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
try {
int data = inputStream.read();
System.out.println("Filter4: " + (char) (data + 3));
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码中,我们使用了Java的管道输入流和输出流来构建一个管道模型,然后创建了四个过滤器线程分别进行数据的处理与转换。在数据从管道输出流中被写入后,它会一步步地经过四个过滤器,直到最终输出到控制台。你可以根据需要修改过滤器的实现逻辑,以实现不同的功能。
阅读全文