请用JAVA编写程序初始化线程池,并向线程池提交任务
时间: 2023-04-04 14:00:36 浏览: 104
您好,我可以回答这个问题。以下是用JAVA编写程序初始化线程池,并向线程池提交任务的示例代码:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// 初始化线程池,设置线程池大小为10
ExecutorService executor = Executors.newFixedThreadPool(10);
// 向线程池提交任务
for (int i = ; i < 100; i++) {
executor.execute(new Task(i));
}
// 关闭线程池
executor.shutdown();
}
static 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.");
}
}
}
希望能对您有所帮助。
阅读全文