【发布时间】:2010-11-17 01:59:35
【问题描述】:
一段多线程代码异步访问资源(例如:文件系统)。
为了实现这一点,我将使用条件变量。假设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() 会立即返回吗?
(我知道使用锁进行读取有些愚蠢,但写入文件也是一种选择。)
【问题讨论】:
标签: java multithreading asynchronous monitor condition-variable