一段多线程代码异步访问资源(例如:文件系统)。
为此,我将使用条件变量。假设FileSystem
是这样的接口:
class FileSystem {
// sends a read request to the fileSystem
read(String fileName) {
// ...
// upon completion, execute a callback
callback(returnCode, buffer);
}
}
我现在有一个应用程序访问FileSystem
. readFile()
假设我可以通过一个方法发出多次读取。该操作应将数据写入传递给它的字节缓冲区。
// constructor
public Test() {
FileSystem disk = ...
boolean readReady = ...
Lock lock = ...
Condition responseReady = lock.newCondition();
}
// the read file method in quesiton
public void readFile(String file) {
try {
lock.lock(); // lets imagine this operation needs a lock
// this operation may take a while to complete;
// but the method should return immediately
disk.read(file);
while (!readReady) { // <<< THIS
responseReady.awaitUninterruptibly();
}
}
finally {
lock.unlock();
}
}
public void callback(int returnCode, byte[] buffer) {
// other code snipped...
readReady = true; // <<< AND THIS
responseReady.signal();
}
这是使用条件变量的正确方法吗?会readFile()
马上回来吗?
(我知道使用锁进行读取有些愚蠢,但写入文件也是一种选择。)