本文目录导读:

- 使用Callable + Future(推荐)
- 使用FutureTask
- 使用CompletableFuture(JDK8+,支持异步回调)
- 使用CountDownLatch + 共享变量
- 使用阻塞队列
- 超时控制和异常处理
- 批量获取多个线程返回值
- 推荐方案
在Java中获取线程返回值有多种方式,下面详细介绍几种主流方法:
使用Callable + Future(推荐)
import java.util.concurrent.*;
public class CallableExample {
public static void main(String[] args) throws Exception {
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(2);
// 创建Callable任务
Callable<String> task = () -> {
Thread.sleep(1000);
return "任务执行完成,返回结果";
};
// 提交任务并获取Future
Future<String> future = executor.submit(task);
// 获取结果(会阻塞直到任务完成)
String result = future.get();
System.out.println(result);
// 关闭线程池
executor.shutdown();
}
}
使用FutureTask
import java.util.concurrent.*;
public class FutureTaskExample {
public static void main(String[] args) throws Exception {
// 创建FutureTask
FutureTask<String> futureTask = new FutureTask<>(() -> {
Thread.sleep(1000);
return "FutureTask执行结果";
});
// 使用线程执行
Thread thread = new Thread(futureTask);
thread.start();
// 获取结果
String result = futureTask.get();
System.out.println(result);
}
}
使用CompletableFuture(JDK8+,支持异步回调)
import java.util.concurrent.*;
public class CompletableFutureExample {
public static void main(String[] args) throws Exception {
// 异步执行任务
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "CompletableFuture结果";
});
// 获取结果
String result = future.get();
System.out.println(result);
// 支持链式调用和回调
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(String::toUpperCase)
.thenAccept(System.out::println);
}
}
使用CountDownLatch + 共享变量
import java.util.concurrent.*;
public class CountDownLatchExample {
private volatile String result;
public static void main(String[] args) throws Exception {
CountDownLatchExample example = new CountDownLatchExample();
example.test();
}
public void test() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
Thread worker = new Thread(() -> {
try {
Thread.sleep(1000);
result = "通过共享变量返回值";
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // 任务完成,计数器减1
}
});
worker.start();
latch.await(); // 等待任务完成
System.out.println(result);
}
}
使用阻塞队列
import java.util.concurrent.*;
public class BlockingQueueExample {
public static void main(String[] args) throws Exception {
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
Thread worker = new Thread(() -> {
try {
Thread.sleep(1000);
queue.put("通过队列返回的结果");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
worker.start();
String result = queue.take(); // 阻塞等待结果
System.out.println(result);
}
}
超时控制和异常处理
import java.util.concurrent.*;
public class TimeoutExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
Thread.sleep(3000);
return "结果";
});
try {
// 设置超时时间
String result = future.get(2, TimeUnit.SECONDS);
System.out.println(result);
} catch (TimeoutException e) {
System.out.println("任务超时");
future.cancel(true); // 取消任务
} catch (Exception e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
批量获取多个线程返回值
import java.util.*;
import java.util.concurrent.*;
public class BatchResultExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(5);
// 创建多个任务
List<Callable<String>> tasks = new ArrayList<>();
for (int i = 0; i < 5; i++) {
final int taskId = i;
tasks.add(() -> {
Thread.sleep(1000);
return "任务" + taskId + "完成";
});
}
// 批量提交并获取所有结果
List<Future<String>> futures = executor.invokeAll(tasks);
// 获取结果
for (Future<String> future : futures) {
String result = future.get();
System.out.println(result);
}
executor.shutdown();
}
}
推荐方案
- JDK 5+:使用
Callable+Future - JDK 8+:使用
CompletableFuture - 简单场景:使用
FutureTask - 需要批量处理:使用
ExecutorService.invokeAll() - 需要同步机制:使用
CountDownLatch
选择哪种方式取决于你的具体需求,如:
- 是否需要超时控制
- 是否需要异步回调
- 是否需要批量处理多个任务
- 代码复杂度要求
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播