我们知道,线程和数据库连接这些资源都是非常宝贵的资源。那么每次需要的时候创建,不需要的时候销毁,是非常浪费资源的。那么我们就可以使用缓存的策略,也就是使用线程池。当然了,线程池也不需要我们来实现,jdk的官方也给我们提供了API。
代码如下:
package com.roocon.thread.t5; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolDemo { public static void main(String[] args) { // 创建线程池 ExecutorService threadPool = Executors.newFixedThreadPool(10); while(true) { threadPool.execute(new Runnable() { // 提交多个线程任务,并执行 @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running .."); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } }
执行结果如下:
pool-1-thread-4 is running .. pool-1-thread-1 is running .. pool-1-thread-6 is running .. pool-1-thread-2 is running .. pool-1-thread-8 is running .. pool-1-thread-3 is running .. pool-1-thread-5 is running .. pool-1-thread-9 is running .. pool-1-thread-10 is running .. pool-1-thread-7 is running ..
线程池的内容还有非常多,这里不再详细地讲解。