山有顶峰 海有彼岸
泰戈尔曾说:"不要着急,最好的总会在最不经意的时候出现,所以不必慌张地去赶路,按自己的节奏,步履不停地走过每个今天。"即使觉得孤军奋战的夜晚漫长又烦闷,你也必须独自熬过这样的夜晚。只有熬得住无人问津的寂寞,才配拥有诗和远方。
正如杨绛先生说得那样:"把圈子变小,把语速放缓,把心放宽,把生活打理简单。用心做好手边的事情,不恋尘世浮华,不被红尘纷扰;看天上的月,吹人间的风。过着平常的日子,该有的,总会有。"
静下心来 沉淀自己
目录
第三方库在并发编程中的应用
除了Java标准库提供的丰富并发工具外,还有许多第三方库专注于特定领域的问题解决,并可能带来额外的功能或性能优势。以下是几个值得注意的第三方库及其特点:
Guava中的ListenableFuture
Guava 是 Google 开发的一套 Java 库集合,它扩展了 Java 标准库的功能。其中 ListenableFuture
接口是对 JDK 中 Future
接口的一种增强. 它允许开发者注册回调函数,在结果计算完成时自动触发这些回调。这意味着可以避免阻塞主线程等待任务完成,而是通过非阻塞的方式处理任务的结果。这不仅提高了程序的响应速度,还简化了异步编程模型。
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.Futures; import java.util.concurrent.Callable; import java.util.concurrent.Executors; public class ListenableFutureExample { public static void main(String[] args) { // 创建一个线程池并装饰为 ListeningExecutorService var execService = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); // 提交一个异步任务 ListenableFuture<String> future = execService.submit((Callable<String>) () -> { try { Thread.sleep(1000); // 模拟耗时操作 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Hello, World!"; }); // 添加成功和失败的回调 Futures.addCallback(future, new FutureCallback<String>() { @Override public void onSuccess(String result) { System.out.println("Task succeeded with result: " + result); } @Override public void onFailure(Throwable t) { System.err.println("Task failed with exception: " + t.getMessage()); } }, MoreExecutors.directExecutor());