Java线程池实际场景问题!!面试必问 求解答
核心线程数7,最大线程数10,等待队列长20
有40个任务 如果40个任务在两秒内全部过来(每个任务执行时间大于两秒),执行拒绝策略,要拒绝多少任务?
答案是10个
从测试结果可以看出,线程池会先将前7个任务(0-6)先放到核心线程池,然后 7 到 26 的任务来了之后被放入了等待队列中,后面id 27-29 因为等待队列满了,开始为这些任务创建新线程 直到到达最大线程数。从30 开始到来的任务都会被拒绝了。
测试代码: public class MyRunnable implements Runnable{ private String id; public MyRunnable(String id) { this.id = id; } @Override public void run() { // System.out.println(Thread.currentThread().getName() + " Start Time = " + new Date()); processCommand(); // System.out.println(Thread.currentThread().getName() + " End Time = " + new Date()); } private void processCommand() { try { System.out.println("ID: " + this.id + " are in process"); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString() { return this.id; } } public class ThreadPoolExecutorDemo { public static final int CORE_POOL_SIZE = 7; public static final int MAX_POOL_SIZE = 10; public static final int QUEUE_CAPACITY = 20; public static final long KEEP_ALIVE_TIME = 1L; public static void main(String[] args) { ThreadPoolExecutor executor = new ThreadPoolExecutor( CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<>(QUEUE_CAPACITY), new ThreadPoolExecutor.AbortPolicy()); for (int i = 0; i < 40; i++) { Runnable worker = new MyRunnable("" + i); try { executor.execute(worker); } catch (Exception e) { System.out.println("Execute ID:" + i + " got exception with details: " + e.getMessage()); } } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("Finished all threads"); } }