java.util.concurrent.RejectedExecutionException

java.util.concurrent.RejectedExecutionException

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@6f94fa3e rejected from java.util.concurrent.ThreadPoolExecutor@5e481248[Running, pool size = 4, active threads = 4, queued tasks = 10, completed tasks = 0]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
	at com.liangyu.c_000.c_005.T.main(T.java:27)

问题描述:提交大量超过线程池处理能力的任务,导致队列饱和,抛出异常

解决方案:把BlockingQueue的大小设置大一点,100个任务设置200个等待队列,如下图所示:

package com.liangyu.c_000.c_005;

import java.util.concurrent.*;

public class T implements Runnable{
    private int count=100;

    public synchronized void run(){
        count--;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" count="+count);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        T t=new T();
//        for (int i=0;i<100;i++){
//            new Thread(t,"Thread"+i).start();
//        }
        ExecutorService poolExecutor = new ThreadPoolExecutor(2, 4, 0l, TimeUnit.SECONDS, new LinkedBlockingQueue(200));
        Future future=null;
        for (int i=0;i<100;i++){
            poolExecutor.execute(t);
        }
        if(!poolExecutor.isShutdown()){
            poolExecutor.shutdown();
        }


    }
}


你可能感兴趣的:(Java并发)