gpt4 book ai didi

java - wait()、notify() - 用于快速读取文件

转载 作者:行者123 更新时间:2023-12-02 10:46:26 25 4
gpt4 key购买 nike

我不明白为什么我的从文件中读取一行的方法运行得这么慢。

下面是我的类(class)的一个例子。它的速度为 10MB/14 秒。同时,主要的延迟是由wait()和notify()引起的。为什么会发生这种情况?

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Reader {
public static final String fileEnd = "=-=-=-=END=-=-=-=";


private String nextLine;

public Reader(File file){
consume(file);
}

public String getLine(){
String line;

synchronized (this){
while (true) {
if(nextLine == null){
notify();


try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if(nextLine.equals(fileEnd)){
return fileEnd;
}
else {
line = nextLine;
nextLine = null;

notify();
break;
}
}
}

return line;
}

private void consume(File file){
Thread thread = new Thread(()->{
final char c = System.getProperty("line.separator").charAt(0);
try (RandomAccessFile aFile = new RandomAccessFile(file, "r")){

FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(10240);

StringBuilder line = new StringBuilder();
while (inChannel.read(buffer) > 0) {
buffer.flip();


for (int i = 0; i < buffer.limit(); i++) {
char as = (char) buffer.get();

if(as==c){
String compliteLine = line.toString();
line = new StringBuilder();

compliteLine = compliteLine.replace("\r", "").replace("\n", "");


synchronized (this){
while (true) {
if (nextLine == null) {
nextLine = compliteLine;


try {
notify();
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

}
else {
line.append(as);
}

}

buffer.clear();
}
inChannel.close();

synchronized (this){
notify();
wait();
nextLine = fileEnd;
notify();
}
}
catch (Exception ignored){ignored.printStackTrace();}
});

thread.setPriority(Thread.MAX_PRIORITY);
thread.setDaemon(true);
thread.start();
}
}

enter image description here

我还尝试对队列 100 的 ArrayBlockingQueue 执行相同的操作。读取同一个文件只需要不到一秒的时间。但这vseravno非常慢。上面的代码是我自己想出来的,目的是为了加快阅读速度,但速度甚至更慢。

问题本身就是为什么代码比队列更高、更慢。又如何加速呢?

最佳答案

在上面的代码中,线程在读取的每一行上都会阻塞。使用ArrayBlockingQueue,只有在从队列中取出这些项目之前从文件中读取了 100 个项目时,线程才会阻塞。根据将项目从队列中取出的处理速度,它可能永远不会阻塞。

如果你想让上面的代码更快,你可以考虑拥有多个缓冲区,这样线程就不需要阻塞每一行。本质上,您需要自己实现一个 BlockingQueue

关于java - wait()、notify() - 用于快速读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52526079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com