java 异步处理接口
时间: 2023-09-02 17:11:57 浏览: 105
用于处理进程的异步接口_Rust_下载.zip
Java中实现异步处理接口的方式有很多,以下是几种常见的方式:
1. 回调函数(callback function):定义一个回调接口,在执行异步操作后,通过回调函数将结果传递给调用方。
```java
public interface Callback<T> {
void onSuccess(T result);
void onFailure(Throwable t);
}
public class AsyncOperation {
public static void doAsyncOperation(Callback<String> callback) {
new Thread(() -> {
// 异步操作
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 结果回调
callback.onSuccess("异步操作结果");
}).start();
}
}
public class Main {
public static void main(String[] args) {
AsyncOperation.doAsyncOperation(new Callback<String>() {
@Override
public void onSuccess(String result) {
System.out.println("异步操作成功,结果为:" + result);
}
@Override
public void onFailure(Throwable t) {
System.out.println("异步操作失败,异常为:" + t.getMessage());
}
});
}
}
```
2. CompletableFuture:Java 8引入了 CompletableFuture 类,可以方便地实现异步操作,支持回调函数、合并操作、异常处理等功能。
```java
public class CompletableFutureDemo {
public static void main(String[] args) {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "异步操作结果";
});
future.thenAccept(result -> System.out.println("异步操作成功,结果为:" + result))
.exceptionally(throwable -> {
System.out.println("异步操作失败,异常为:" + throwable.getMessage());
return null;
});
}
}
```
3. Future:Java 5引入的Future接口可以获取异步操作的结果,但是不支持回调函数和异常处理。
```java
public class FutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "异步操作结果";
});
String result = future.get();
System.out.println("异步操作成功,结果为:" + result);
executor.shutdown();
}
}
```
以上是几种常见的实现异步处理接口的方式,具体选择哪种方式取决于具体的需求和场景。
阅读全文