Executors.newFixedThreadPool 线程执行代码
时间: 2023-10-25 22:59:58 浏览: 106
67.多线程代码.zip
Sure! Here's an example of how you can use `Executors.newFixedThreadPool` to execute code using a fixed number of threads:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// Create a fixed thread pool with 5 threads
ExecutorService executor = Executors.newFixedThreadPool(5);
// Submit tasks for execution
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " executed by " + Thread.currentThread().getName());
});
}
// Shutdown the executor
executor.shutdown();
}
}
```
In this example, we create a fixed thread pool with 5 threads using `Executors.newFixedThreadPool(5)`. We then submit 10 tasks for execution using the `executor.submit()` method. Each task is a lambda expression that prints a message indicating the task ID and the name of the thread that executes it. Finally, we shut down the executor using `executor.shutdown()` to gracefully terminate the threads once all tasks have completed.
Please note that this is a simplified example, and in a real-world scenario, you would typically handle the returned `Future` objects from the `submit()` method to track task completion or obtain results.
阅读全文