多线程工具类与应用

多线程工具类:

/**
 * ThreadPoolUtil.java
 */
package com.lbs.util;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
/**
 * 
 * <p>ClassName: ThreadPoolUtil</p>
 * <p>Description: TODO</p>
 */
public class ThreadPoolUtil {
    
    
    /**
     * 设置默认初始线程池的大小
     */
    private static final int COREPOOLSIZE = 24;
    /**
     * MAXIMUMPOOLSIZE
     */
    private static final int MAXIMUMPOOLSIZE = 100;
    /**
     * QUEUESIZE
     */
    private static final int QUEUESIZE = 2000;
    /**
     * KEEPLIVETIME
     */
    private static final long KEEPLIVETIME = 5L;
    /**
     * queue
     */
    private static final BlockingQueue<Runnable> QUEUE = new ArrayBlockingQueue<Runnable>(QUEUESIZE);
    /**
     * CALLERRUNSHANDLER
     */
    private static final RejectedExecutionHandler CALLERRUNSHANDLER = new CallerRunsPolicy();
    /**
     * instance
     */
    private static ThreadPoolUtil instance = null;
    /**
     * boundedThreadPool
     */
    private ExecutorService boundedThreadPool;
    /**
     * 
     * <p>Description: TODO</p>
     */
    private ThreadPoolUtil() {
        // 创建有界大小的线程池
        this.boundedThreadPool = new ThreadPoolExecutor(COREPOOLSIZE, MAXIMUMPOOLSIZE, KEEPLIVETIME, TimeUnit.SECONDS,
                QUEUE, CALLERRUNSHANDLER);
    }
    /**
     * 提供唯一实例
     * 
     * @return instance
     */
    public static ThreadPoolUtil getInstance() {
        if (instance == null) {
            synchronized (ThreadPoolUtil.class) {
                if (instance == null) {
                    instance = new ThreadPoolUtil();
                }
            }
        }
        return instance;
    }

    /**
     * 
     * <p>Description: TODO</p>
     * @return ExecutorService
     */
    public ExecutorService getBoundedThreadPool() {
        return this.boundedThreadPool;
    }
}

应用举例:

 

posted @ 2020-06-04 14:25  AlphaJunS  阅读(301)  评论(0编辑  收藏  举报