直接上用法代码:
1 import java.util.concurrent.LinkedBlockingQueue; 2 import java.util.concurrent.ThreadPoolExecutor; 3 import java.util.concurrent.TimeUnit; 4 5 public class Fruit { 6 7 public static void main(String[] args) throws InterruptedException{ 8 ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); 9 threadPool.execute(new Runnable(){ 10 public void run(){ 11 //do something 12 } 13 }); 14 } 15 }
看看new一个ThreadPool用的参数:
1.第一个参数10表示这个线程池初始化了10个线程在里面工作
2. 第二个参数15表示如果10个线程不够用,就自动增加到最多15个线程
3. 第三个参数60和第四个参数TimeUnit.SECONDS表示经过60秒,多出来的线程都没有接到任务干,就回收,使线程池保持为10个线程
4. 第五个参数new LinkedBlockingQueue<Runnable>()是用来放任务的集合
execute方法用于添加新任务
Written on Sept. 30th, 2019