Java异步调用接口的方法有以下几种:
1、使用CompletableFuture
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { // 模拟耗时操作 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello, CompletableFuture!"; }); System.out.println("异步任务执行中..."); String result = future.get(); // 阻塞等待异步任务完成,获取结果 System.out.println("异步任务结果:" + result); } }
2、使用ExecutorService
import java.util.concurrent.*; public class ExecutorServiceDemo { public static void main(String[] args) { ExecutorService executorService = Executors.newSingleThreadExecutor(); // 创建一个单线程的线程池 Future<String> future = executorService.submit(() -> { // 提交一个异步任务 // 模拟耗时操作 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello, ExecutorService!"; }); executorService.shutdown(); // 关闭线程池,不再接受新的任务 try { String result = future.get(); // 阻塞等待异步任务完成,获取结果 System.out.println("异步任务结果:" + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }
3、使用Callable和FutureTask
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class CallableFutureTaskDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { Callable<String> callable = new Callable<String>() { @Override public String call() throws Exception { // 模拟耗时操作 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello, Callable and FutureTask!"; } }; FutureTask<String> futureTask = new FutureTask<>(callable); // 将Callable封装成FutureTask对象,以便于使用get方法获取异步任务结果 Thread thread = new Thread(futureTask); // 创建一个新线程来执行异步任务 thread.start(); // 启动线程,执行异步任务 System.out.println("异步任务执行中..."); String result = futureTask.get(); // 通过FutureTask的get方法阻塞等待异步任务完成,获取结果(如果异步任务还没完成,这里会阻塞等待) System.out.println("异步任务结果:" + result); } }
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/124950.html