gpt4 book ai didi

java - 多线程代码和条件变量的使用

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:32 26 4
gpt4 key购买 nike

一段多线程代码异步访问资源(例如:文件系统)。

为了实现这一点,我将使用条件变量。假设 FileSystem 是一个如下接口(interface):

class FileSystem {
// sends a read request to the fileSystem
read(String fileName) {
// ...
// upon completion, execute a callback
callback(returnCode, buffer);
}
}

我现在有一个访问文件系统的应用程序。假设我可以通过 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() 会立即返回吗?

(我知道使用锁进行读取有些愚蠢,但写入文件也是一种选择。)

最佳答案

您的问题遗漏了很多内容(即没有具体提及线程),但无论如何我都会尝试回答。

锁和条件变量都不提供后台功能——它们只是用于线程等待来自其他线程的信号。尽管您没有提及,但 disk.read(file) 方法可以生成一个线程来执行 IO,然后立即返回,但调用者无论如何都会坐在 readReady 循环中,这似乎毫无意义。如果调用者必须等待,那么它可以自行执行 IO。

更好的模式可能是使用 Java 5 Executors 服务之类的东西:

 ExecutorService pool = Executors.newFixedThreadPool(int numThreads);

然后,您可以调用pool.submit(Callable),它将提交要在另一个线程的后台执行的作业(当池下一个可用时)。 Submit 返回一个 Future ,调用者可以使用它来调查后台任务是否已完成。它也可以返回结果对象。并发类会为您处理锁定和条件信号/等待逻辑。

希望这有帮助。

附:另外,您应该使 readReady 具有 volatile ,因为它没有同步。

关于java - 多线程代码和条件变量的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4200837/

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