执行逻辑:
1、如果当前运行的线程少于corePoolSize,会创建新的线程来执行新的任务;
2、如果运行的线程个数等于或者大于corePooolSize,则会将提交的任务存放在阻塞队列中;
3、如果当前的阻塞队列已经满了,则会创建新的非核心线程来执行任务,会先于阻塞队列里的线程执行;
4、如果正在运行的线程的个数超过了最大线程数(maximumPoolSize),则会使用拒绝策略RejectedExecutionHandler来进行处理。
测试验证代码如下:
public class ThreadPoolExecutorDemo { public static void main(String[] args) { ExecutorService executorService=new ThreadPoolExecutor(3,6,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(4)); for (int i = 0; i < 10; i++) { if(i>=7){ executorService.execute(new Task2()); }else{ executorService.execute(new Task()); } executorService.shutdown(); } }
public class Task implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"任务一"+"running"); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"任务一"+"end"); // System.out.println(System.currentTimeMillis()); } }
public class Task2 implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"任务二"+"running"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"任务二"+"end"); // System.out.println(System.currentTimeMillis()); } }