用java写一个动态多线程,带动态线程池的例子
时间: 2023-02-26 12:00:58 浏览: 133
好的,这是一个使用 Java 实现的动态多线程、带动态线程池的示例代码:
```
import java.util.concurrent.*;
public class DynamicThreadPool {
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int KEEP_ALIVE_TIME = 5;
private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(5);
private static ThreadPoolExecutor threadPoolExecutor;
public static void main(String[] args) {
threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TIME_UNIT, WORK_QUEUE);
for (int i = 1; i <= 20; i++) {
final int taskId = i;
threadPoolExecutor.execute(() -> {
System.out.println("Task " + taskId + " is running on " + Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("Current pool size: " + threadPoolExecutor.getPoolSize());
}
threadPoolExecutor.shutdown();
}
}
```
在上面的代码中,我们创建了一个线程池,它的核心线程数为 5,最大线程数为 10,空闲线程存活时间为 5 秒,工作队列的大小为 5。每提交一个任务,都会打印当前线程池的大小。
运行代码后,你会发现,当线程池的大小达到核心线程数时,新的任务会被放到工作队列中;当工作队列满了,再有新任务时,线程池会创建新线程来处理任务,直到线程池中的线程数达到最大
阅读全文