请写一段Java并发编程代码
时间: 2024-02-03 16:14:57 浏览: 70
并发编程Java代码示例.zip
以下是一个简单的Java并发编程代码,使用线程池实现多线程任务执行:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentProgrammingExample {
public static void main(String[] args) {
// 创建线程池,指定线程数量为10
ExecutorService executorService = Executors.newFixedThreadPool(10);
// 提交10个任务给线程池执行
for (int i = 0; i < 10; i++) {
executorService.submit(new Task(i));
}
// 关闭线程池
executorService.shutdown();
}
}
class Task implements Runnable {
private int taskId;
public Task(int taskId) {
this.taskId = taskId;
}
@Override
public void run() {
System.out.println("Task " + taskId + " is running.");
}
}
```
此代码使用线程池同时执行10个任务,并在任务执行完成后关闭线程池。
阅读全文