1. Callable 接口
Callable 接口和 Runnable 接口类似,但 Callable 接口可以返回一个值,并且可以抛出异常。可以使用 Callable 接口实现带返回值的多线程程序。Callable 接口定义如下:
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
2. Future 接口
Future 接口用于表示一个异步计算的结果(静态对象)。Future 接口提供了获取计算结果的方法。可以将计算任务提交给 ExecutorService 进行异步处理,并通过 Future 接口获得结果,定义:
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
3.使用示例
import java.util.concurrent.*;
public class CallableAndFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建一个线程池
ExecutorService executor = Executors.newFixedThreadPool(2);
// 创建两个 Callable 对象
Callable<Integer> task1 = () -> {
// 模拟耗时操作
Thread.sleep(1000);
return 10;
};
Callable<String> task2 = () -> {
// 模拟耗时操作
Thread.sleep(2000);
return "Hello, World!";
};
// 使用 submit() 方法提交 Callable 对象到线程池,并获取 Future 对象
Future<Integer> future1 = executor.submit(task1);
Future<String> future2 = executor.submit(task2);
// 使用 get() 方法获取 Future 对象的结果
Integer result1 = future1.get();
String result2 = future2.get();
// 处理结果
System.out.println("Result 1: " + result1);
System.out.println("Result 2: " + result2);
// 关闭线程池
executor.shutdown();
}
}
4.总结
总的来说就是callable进行运算将结果放入future中,future.get来进行阻塞
1170





