题目
Java 中获取线程返回值有几种方法
答案
@[toc]
---
## 自定义 get 方法
在 run 方法中设置返回值,然后通过实现一个 get 方法来获取返回值。线程可以通过调用 join 方法来等待线程结束后再通过 get 方法获取 run 方法的返回值。
```java
class MyRunnable implements Runnable {
private int result;
public void run() {
// 计算结果并赋值给 result
result = 1 + 2 + 3 + 4 + 5;
}
public int getResult() {
return result;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 启动线程
thread.join(); // 等待线程执行完毕
int result = runnable.getResult();
System.out.println(result); // 输出:15
}
}
```
## Callable + Future
Callable 接口允许线程返回一个值。Future 接口则提供了一个 get 方法,用于获取 Callable 的返回值。通过 `ExecutorService.submit(Callable<T> task)` 方法提交 Callable 任务并获取 Future 对象,然后使用 `Future.get()` 方法来等待任务完成并获取返回值。
```java
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
// 计算结果并返回
return 1 + 2 + 3 + 4 + 5;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<Integer> callable = new MyCallable();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(callable);
int result = future.get();
System.out.println(result); // 输出:15
executor.shutdown();
}
}
```
## Callable + FutureTask
FutureTask 可以在构造函数中接受一个 Callable 对象,并将其返回值存储在 FutureTask 对象中。通过调用 FutureTask.get() 方法获取线程返回值。
```java
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
// 计算结果并返回
return 1 + 2 + 3 + 4 + 5;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<Integer> callable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
int result = futureTask.get();
System.out.println(result); // 输出:15
}
}
```
## CompletableFuture
> `CompletableFuture` 可以看做是一种更高级的 `Future`,比于普通的 `Future`,`CompletableFuture` 提供了更多的方法和功能,使得使用起来更加方便灵活,它支持链式调用、组合多个 `CompletableFuture`、超时控制、异常处理等功能。通过 `CompletableFuture` 的 `get` 方法,也可以获取线程的返回值。
`CompletableFuture` 提供了一种异步编程的方式,可以在任务完成时异步触发回调,获取任务的返回值。使用 `CompletableFuture.supplyAsync(Supplier<U> supplier)` 方法创建一个异步任务,并使用 `CompletableFuture.get()` 方法等待任务完成并获取返回值。
```java
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
// 计算结果并返回
return 1 + 2 + 3 + 4 + 5;
});
int result = future.get();
System.out.println(result); // 输出:15
}
}
```
