封装一个异步执行器Java
时间: 2023-07-25 19:32:25 浏览: 249
好的,我可以为您封装一个异步执行器Java。以下是示例代码:
```java
import java.util.concurrent.*;
public class AsyncExecutor {
private final ExecutorService executorService;
public AsyncExecutor(int maxThreads) {
executorService = Executors.newFixedThreadPool(maxThreads);
}
public <T> Future<T> submit(Callable<T> task) {
return executorService.submit(task);
}
public Future<?> submit(Runnable task) {
return executorService.submit(task);
}
public void shutdown() {
executorService.shutdown();
}
}
```
使用示例:
```java
AsyncExecutor asyncExecutor = new AsyncExecutor(10);
Future<Integer> future = asyncExecutor.submit(() -> {
Thread.sleep(1000);
return 42;
});
System.out.println("Task submitted");
try {
int result = future.get();
System.out.println("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
asyncExecutor.shutdown();
```
这个异步执行器使用了Java标准库中的ExecutorService和Future,允许您提交任务并异步执行。您可以根据需要调整线程池的大小。注意在使用完异步执行器后需要调用shutdown()方法关闭线程池。
阅读全文