【发布时间】:2012-09-30 20:45:47
【问题描述】:
我是 java 并发编程的新手。
我需要阅读、分析和处理一个增长极快的日志文件,所以我必须 快速地。 我的想法是读取文件(逐行)并匹配我想要的相关行 将这些行传递给可以对该行进行进一步处理的单独线程。 在下面的示例代码中,我将这些线程称为“IOThread”。
我的问题是 IOthread.run() 中的 BufferedReader readline 显然永远不会返回。 在线程内读取 Stream 的工作方式是什么? 还有比下面的方法更好的方法吗?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
class IOThread extends Thread {
private InputStream is;
private int t;
public IOThread(InputStream is, int t) {
this.is = is;
this.t = t;
System.out.println("iothread<" + t + ">.init");
}
public void run() {
try {
System.out.println("iothread<" + t + ">.run");
String line;
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is));
while ((line = streamReader.readLine()) != null) {
System.out.println("iothread<" + t + "> got line " + line);
}
System.out.println("iothread " + t + " end run");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Stm {
public Stm(String filePath) {
System.out.println("start");
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
PipedOutputStream po1 = new PipedOutputStream();
PipedOutputStream po2 = new PipedOutputStream();
PipedInputStream pi1 = new PipedInputStream(po1);
PipedInputStream pi2 = new PipedInputStream(po2);
IOThread it1 = new IOThread(pi1,1);
IOThread it2 = new IOThread(pi2,2);
it1.start();
it2.start();
// it1.join();
// it2.join();
String line;
while ((line = reader.readLine()) != null) {
System.out.println("got line " + line);
if (line.contains("aaa")) {
System.out.println("passing to thread 1: " + line);
po1.write(line.getBytes());
} else if (line.contains("bbb")) {
System.out.println("passing to thread 2: " + line);
po2.write(line.getBytes());
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Stm(args[0]);
}
}
一个示例输入文件是:
line 1
line 2
line 3 aaa ...
line 4
line 5 bbb ...
line 6 aaa ...
line 7
line 8 bbb ...
line 9 bbb ...
line 10
以输入文件的文件名作为参数调用上述代码。
【问题讨论】:
-
可能
PipedInputStream期望读取更多字节...您可以close()PipedOutputStream进行测试吗? -
哦,无论如何我和 Sanjay 在一起......使用来自进程内通信的输入流和输出流很麻烦。将受影响的行传递给线程不是更好吗?
-
我在 run() 方法中的
while ((line = streamReader.readLine()) != null)行上遇到了java.io.IOException: Write end dead异常。
标签: java multithreading concurrency readline