20240619-James-快速鸟瞰并发编程, 呕心沥血整理的架构技术(第3篇)

其实 功能接口如下

接口 描述
Runnable run()方法没有返回值。
Callable call方法有返回值。

Future

Future是对于具体的Runnable任务或Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。

ExecutorService使用Future作为返回类型。

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future future = executorService.submit(() -> “结果”);
try {
String result = future.get(1L, TimeUnit.SECONDS);
System.out.println(“结果为 '” + result + “'.”);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
assert future.isDone();

ReentrantLock锁

java.util.concurrent.locks软件包括了经常使用到的Lock接口。ReentrantLock类其实也实现了synchronized关键字的功能,还提供了其它功能,例如获取有关锁的状态,非阻塞tryLock

你可能感兴趣的:(架构,java,网络)