threadpooltaskexecutor使用例子
时间: 2023-09-13 16:14:00 浏览: 88
Sure, I can provide you with an example of using ThreadPoolTaskExecutor in Java:
```
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
public class ThreadExecutorExample {
public static void main(String[] args) {
// Create a task executor with maximum pool size 5
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(10);
// Execute 10 tasks
for (int i = 0; i < 10; i++) {
executor.execute(new Runnable() {
public void run() {
System.out.println("Task executed by thread " + Thread.currentThread().getName());
}
});
}
// Shutdown the executor
executor.shutdown();
}
}
```
This example creates a ThreadPoolTaskExecutor object with a maximum pool size of 5 and executes 10 tasks using the execute() method. The tasks are executed by different threads from the thread pool, and the output shows the thread names. Finally, the executor is shut down using the shutdown() method.
阅读全文