java.util.concurrent.ThreadPoolExecutor 测试 main 使用submit
时间: 2023-11-23 12:56:31 浏览: 98
以下是使用java.util.concurrent.ThreadPoolExecutor测试main方法使用submit的示例:
```java
import java.util.concurrent.*;
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
int corePoolSize = 5;
int maxPoolSize = 10;
long keepAliveTime = 5000;
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, workQueue);
for (int i = 0; i < 20; i++) {
threadPoolExecutor.submit(new Task(i));
}
threadPoolExecutor.shutdown();
}
static class Task implements Runnable {
private int taskId;
public Task(int taskId) {
this.taskId = taskId;
}
@Override
public void run() {
System.out.println("Task #" + this.taskId + " is running.");
}
}
}
```
在这个示例中,我们创建了一个ThreadPoolExecutor对象,并使用submit方法向线程池提交了20个任务。每个任务都是一个简单的Runnable对象,它只是打印一条消息。
注意,我们在最后调用了shutdown方法来关闭线程池。这是非常重要的,因为如果不关闭线程池,程序将一直运行下去。
阅读全文