gpt4 book ai didi

Java 可等待对象容器

转载 作者:行者123 更新时间:2023-12-01 09:20:04 24 4
gpt4 key购买 nike

现有框架是否实现了以下方法?

public class WaitableContainer<T> {
private T object;
public <T> peekAwait() {...} // returns object if object !=null or makes the caller thread sleep until object != null
public actuate(T object) {
this.object = object; // here all sleeping threads must awake and receive the new object
}
}

需要某种对象包装器,它将使调用者线程一直运行,直到另一个线程设置该对象。

最佳答案

这听起来像 CompletableFuture

// container.actuate(o); becomes
future.complete(o);

// container.peekAwait(); becomes
future.get();

如果您无法使用 Java 8,FutureTask是一个不错的解决方法选择,但您不需要显式设置它,而是提供一个返回您想要设置的值的 Callable。

final FutureTask<Object> lazyLoadedData = new FutureTask<>(() -> expensiveIO());

...

if (!lazyLoadedData.isDone()) {
synchronized(lazyLoadedData) {
if (!lazyLoadedData.isDone()) {
// run() does the computation and sets the data
// essentially, lazyLoadedData.set(expensiveIO())
lazyLoadedData.run();
}
}
}
// Data is available
lazyLoadedData.get();

如果您计划让 ExecutorService 执行此操作,它已经返回一个 Future;

final FutureTask<Object> future = executorService.submit(() -> expensiveIO());

// Now you just need to call get()
future.get();

关于Java 可等待对象容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221492/

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