Spring 提供了 TaskExecutor 接口作为处理 Executor 的抽象。 TaskExecutor的实现类如下:
- SimpleAsyncTaskExecutor: This starts a new thread and executes it asynchronously. It does not reuse the thread.
- SyncTaskExecutor: This executes each task synchronously in the calling thread. It does not reuse the thread.
- ConcurrentTaskExecutor: This exposes bean properties for configuring java.util.concurrent.Executor.
- SimpleThreadPoolTaskExecutor: This is a subclass of SimpleThreadPool of Quartz, which listens to Spring's life cycle callbacks.
- ThreadPoolTaskExecutor: This exposes bean properties for configuring java.util.concurrent.ThreadPoolExecutor and wraps it in TaskExecutor.
- TimerTaskExecutor: This implements a single TimerTask class as its backing implementation. It executes methods as synchronous in a separate thread.
- WorkManagerTaskExecutor: This uses the CommonJ WorkManager interface as its backing implementation.
让我们看一个在 Spring 应用程序中使用 SimpleAsyncTaskExecutor 执行任务的简单示例。它为每个任务提交创建一个新线程并以异步方式运行。
这是配置文件:
这是我们将 5 任务分配给 TaskExecutor 的 bean 类:
以下是从 main 方法执行任务的代码:
当我们编译并运行前面的类时,我们将得到以下输出。在这里,我们可以看到创建了五个线程,它们异步执行任务: