使用 Callable 和 Future 创建线程

使用 Callable 和 Future 创建线程 实际上使用 Callable 和 Future 创建线程从 Java 5 开始Java 提供了 Callable 接口该接口怎么看都像是 Runnable 接口的增强版Callable 接口提供了一个 call () 方法可以作为线程执行体但 call () 方法比 run () 方法功能更强大。以下是一个使用 Callable 和 Future 创建线程的 Java 多线程代码示例import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class CallableExample { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor Executors.newSingleThreadExecutor(); // 创建线程池 CallableString callable new MyCallable(); // 创建Callable任务 FutureString future executor.submit(callable); // 提交任务并获取Future对象 System.out.println(等待任务执行结果...); String result future.get(); // 获取任务执行结果这是一个阻塞方法直到任务执行完成才会返回结果 System.out.println(任务执行结果 result); executor.shutdown(); // 关闭线程池 } } class MyCallable implements CallableString { Override public String call() throws Exception { Thread.sleep(3000); // 模拟耗时操作 return Hello, World!; } }在这个示例中我们创建了一个 Callable 任务 MyCallable 并将其提交给一个线程池 ExecutorService 。线程池会返回一个 Future 对象我们可以使用它来获取任务的执行结果。在主线程中我们调用 Future 对象的 get 方法来获取结果这是一个阻塞方法直到任务执行完成才会返回结果。最后我们关闭线程池。