// 方法1: 使用线程池和Future实现异步
import java.util.concurrent.*;
public class AsyncExample1 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(2);
// 提交任务并获取Future对象
Future<String> future = executor.submit(() -> {
// 模拟耗时操作
Thread.sleep(2000);
return "Task completed";
});
// 可以做其他事情,然后在需要的时候获取结果
System.out.println("Doing other tasks...");
System.out.println("Result: " + future.get()); // 阻塞直到结果返回
executor.shutdown();
}
}
// 方法2: 使用CompletableFuture实现异步
import java.util.concurrent.CompletableFuture;
public class AsyncExample2 {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
// 模拟耗时操作
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Task completed";
});
// 可以做其他事情,然后在需要的时候获取结果
System.out.println("Doing other tasks...");
System.out.println("Result: " + future.get()); // 非阻塞方式等待结果
// 也可以使用thenApply、thenAccept等方法链式调用
CompletableFuture<Void> result = future.thenAccept(System.out::println);
result.join(); // 等待所有操作完成
}
}
// 方法3: 使用回调函数实现异步
public class AsyncExample3 {
public static void main(String[] args) throws InterruptedException {
MyAsyncTask task = new MyAsyncTask();
task.executeAsync(result -> {
System.out.println("Callback received result: " + result);
});
// 主线程可以继续执行其他任务
System.out.println("Doing other tasks...");
Thread.sleep(3000); // 模拟主线程继续工作
}
}
class MyAsyncTask {
public void executeAsync(MyCallback callback) {
new Thread(() -> {
try {
// 模拟耗时操作
Thread.sleep(2000);
String result = "Task completed";
callback.onComplete(result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
interface MyCallback {
void onComplete(String result);
}
使用线程池和Future实现异步:
submit方法提交任务。Future对象用于获取任务的结果。future.get()会阻塞当前线程,直到任务完成。使用CompletableFuture实现异步:
CompletableFuture是Java 8引入的类,提供了更灵活的异步编程模型。supplyAsync方法用于异步执行任务,get方法同样会阻塞等待结果。thenApply、thenAccept等方法进行链式调用,实现非阻塞的操作。使用回调函数实现异步:
MyCallback,并在任务完成后通过回调函数传递结果。这些方法都可以实现异步操作,具体选择哪种方法取决于你的需求和代码风格。
上一篇:java获取ip地址
下一篇:java+ai
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站