ThreadPoolExecutor

创建线程池
拒绝策略
1.ThreadPoolExecutor.DiscardPolicy()
对拒绝任务直接无声抛弃,没有异常信息。
ThreadPoolExecutor.AbortPolicy()
对拒绝任务抛弃处理,并且抛出异常。
ThreadPoolExecutor.CallerRunsPolicy()
这个策略重试添加当前的任务,他会自动重复调用 execute() 方法,直到成功。
ThreadPoolExecutor.DiscardOldestPolicy()
对拒绝任务不抛弃,而是抛弃队列里面等待最久的一个线程,然后把拒绝任务加到队列。

public class QueryLogManager {

    //private final static Logger logger = LoggerFactory.getLogger(QueryLogManager.class);

    private static final int corePoolSize = 2;//核心线程个数

    private static final int maximumPoolSize = 10;//线程池最大线程数量

    private static final int maximumQueueSize = 500;//阻塞队列最大长度

    private static final long keepAliveTime = 60000L;//空闲线程的存活时间

    private static final TimeUnit unit = TimeUnit.MILLISECONDS;//表示keepAliveTime的单位(毫秒)

    private static ExecutorService executor = new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            unit,
            new LinkedBlockingQueue(maximumQueueSize),
            new ThreadPoolExecutor.DiscardPolicy()//丢弃被拒绝的任务,不做处理(拒绝策略)
    );

    public static void create(Runnable task) {
        executor.submit(task);
    }
}

创建处理对象

public class Task implements Runnable {

    private String methodName;
    private Integer res;

    public Task(String methodName, Integer res) {
        this.methodName = methodName;
        this.res = res;
    }
    //进行处理
    public void run() {
        System.out.println(methodName + ": " +(res + 1));
    }
}

测试

public class TestMain {

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            TestName(i);
        }
    }
    private static void TestName(Integer num) {
        QueryLogManager.create(new Task(Thread.currentThread().getStackTrace()[1].getClassName(), num));
    }
}

你可能感兴趣的:(Java多线程)