赞
踩
如果想要一次性并发执行多个任务,可以使用 Java 并发编程中的线程池来实现。具体步骤如下:
- public class Task implements Runnable {
- private int id;
-
- public Task(int id) {
- this.id = id;
- }
-
- @Override
- public void run() {
- System.out.println("Task " + id + " is running at " + new Date());
- }
- }
@RestController
public class TaskController {
private static final int MAX_THREADS = 10;
private static final int QUEUE_CAPACITY = 100;
private ThreadPoolExecutor executor = new ThreadPoolExecutor(
MAX_THREADS,
MAX_THREADS,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(QUEUE_CAPACITY)
);
@GetMapping("/tasks")
public String triggerTasks() {
// 添加 2 个任务到线程池中
executor.execute(new Task(1));
executor.execute(new Task(2));
return "Tasks are triggered!";
}
}
在上述示例代码中,我们通过 ThreadPoolExecutor 类创建一个最大线程数为 10,任务队列容量为 100 的线程池。当访问 /tasks URL 时,添加两个任务到线程池中。
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这样,当你访问 http://localhost:8080/tasks 时,就会并发地执行两个任务。线程池会自动管理线程的数量、任务队列和线程的生命周期。如果需要执行更多任务,只需添加更多的任务到线程池中即可
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。