gpt4 book ai didi

java - 如何延迟方法返回直到文件完全读取

转载 作者:太空宇宙 更新时间:2023-11-04 06:42:10 24 4
gpt4 key购买 nike

考虑以下代码示例,其中我删除了所有错误处理代码以保持可读性:

public class MyClass {

protected Something myAttribute;
protected boolean busy = true;

public ReactiveLogger() {
new Thread(new FileListener()).start();
}

private class FileListener implements Runnable {

@Override
public void run() {
RandomAccessFile raf = new RandomAccessFile(LOG_FILE, "rw");
while (true) {
final String line = cutFirstLine(raf);
if (line == null) {
busy = false;
Thread.sleep(1000);
} else {
busy = true;
// handeLogMessage changes myAttribute
handleLogMessage(line);
}
}
}

// definition of cutFirstLine etc.

}

// definition of handleLogMessage etc.

public Something getSomething() {
while (busy) {
Thread.sleep(100);
}
return myAttribute;
}

}

因此,我的类 MyClass 在后台(在另一个线程中)读取日志文件,并用从日志文件中读取的每一行更新属性 myAttribute。只要日志文件中有任何条目并且更新了我的属性,getter 函数 getMyAttribute() 的返回就应该延迟。一旦日志文件中不再有任何条目,getMyAttribute() 就应该返回 myAttribute

尽管此代码示例可以按要求工作,但它似乎不是最优雅的解决方案。根本不清楚线程应该 hibernate 多长时间才能获得最佳结果。如果只是在 getter 函数中删除对 Thread.sleep 的调用,程序就会卡住。但如果我将 sleep 方法的值设置得太高,执行时间也会太长。

我怎样才能以更好的方式实现同​​样的目标?我已经看过 Java 多线程/并发编程资源,但似乎没有什么(如 Java 的 synchronized)适合这种情况。

最佳答案

多亏了这些评论,我再次查看了 synchronized/wait()/notify() 。所以这是另一个有效且更优雅的解决方案:

public class MyClass {

protected Something myAttribute;
protected boolean busy = true;
protected final Object lock = new Object();

public ReactiveLogger() {
new Thread(new FileListener()).start();
}

private class FileListener implements Runnable {

@Override
public void run() {
RandomAccessFile raf = new RandomAccessFile(LOG_FILE, "rw");
while (true) {
final String line = cutFirstLine(raf);
if (line == null) {
busy = false;
synchronized (lock) {
lock.notifyAll();
}
Thread.sleep(1000);
} else {
busy = true;
// handeLogMessage changes myAttribute
handleLogMessage(line);
}
}
}

// definition of cutFirstLine etc.

}

// definition of handleLogMessage etc.

public Something getSomething() {
synchronized (lock) {
while (busy) {
lock.wait();
}
}
return myAttribute;
}

}

但可能仍然有更好的解决方案。 Java 杰出人物 Josh Bloch 在他的《Effective Java 2nd Edition》一书中严格建议不要使用这些方法(来自 this answer):

Given the difficulty of using wait and notify correctly, you should use the higher-level concurrency utilities instead [...] using wait and notify directly is like programming in "concurrency assembly language", as compared to the higher-level language provided by java.util.concurrent. There is seldom, if ever, reason to use wait and notify in new code.

关于java - 如何延迟方法返回直到文件完全读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24551244/

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