concurrent threads

/**
* 线程处理类
*/
public class ExecutorProcessPool {
private ExecutorService executor;
private static ExecutorProcessPool pool = new ExecutorProcessPool();
private final int threadMax = 50;

private ExecutorProcessPool() {
executor = ExecutorServiceFactory.getInstance().createFixedThreadPool(threadMax);
}

public static ExecutorProcessPool getInstance() {
return pool;
}
/**
* 获得当前活动线程数
* @return
*/
public int getActiveCount(){
return ((ThreadPoolExecutor)executor).getActiveCount();
}
/**
* Shut down the thread pool, what is to be explained here is: after calling the method to close the thread pool, the thread pool will execute all tasks in the queue before exiting
*
*/
public void shutdown() {
executor.shutdown();
}

/**
* Submit the task to the thread pool, you can receive the thread return value
*
* @param task
* @return
*/
public Future<?> submit(Runnable task) {
return executor.submit(task);
}

/**
* Submit the task to the thread pool , can receive the thread return value
*
* @param task
* @return
*/
public Future<?> submit(Callable<?> task) {
return executor.submit(task);
}

/**
* Submit the task directly to the thread pool, no return value
*
* @param task
*/
public void execute(Runnable task) {
executor.execute(task);
}

}


ExecutorProcessPool pool = ExecutorProcessPool.getInstance();
debug("pool.getActiveCount()=="+pool.getActiveCount());
ServiceResponse serviceResponse = new ServiceResponse ();
Map map = new HashMap();
if(pool.getActiveCount()>=50){
debug("Maximum threads exceeded=="+pool.getActiveCount());
map.put("result", "Concurrency Exceeded the maximum number of threads, please try later");
}else{
pool.submit(new confirmApplicationThreadNewTask(serviceRequest));
map.put("result", "Processing, please check later");
}
serviceResponse. setModel(map);


public class confirmApplicationThreadNewTask implements Callable<String> {
private ServiceRequest serviceRequest;

public confirmApplicationThreadNewTask(ServiceRequest serviceRequest){
this.serviceRequest=serviceRequest;
}

@Override
public String call() throws Exception {
ServiceResponse serviceResponse = confirmApplicationNew(serviceRequest);
Map map = serviceResponse.getModel();
ConfirmAppModel confirmAppModel = new ConfirmAppModel();
confirmAppModel.setApplicationNo(map.get("applicationNo")+"");
confirmAppModel.setReturnCode(map.get String json = JSON.toJSONString(map, true); 
confirmAppModel.setJson(json);

APIServiceUtil.getAPIClientService(context).confirmApplicationThreadNew(confirmAppModel);
return null;
}
}


public class ExecutorServiceFactory {
private static ExecutorServiceFactory executorFactory = new ExecutorServiceFactory();
    /**
     * Timed task thread pool
     */
    private ExecutorService executors;

    private ExecutorServiceFactory() {
   
    }

    /**
     * Get ExecutorServiceFactory
     *
     * @return
     */
    public static ExecutorServiceFactory getInstance() {
        return executorFactory;
    }

    /**
     * Creates a thread pool that can schedule commands to run after a given delay or periodically.
     *
     * @return
     */
    public ExecutorService createScheduledThreadPool() {
        // Number of CPUs
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        // Create
        executors = Executors.newScheduledThreadPool(availableProcessors * 10, getThreadFactory());
        return executors;
    }

    /**
     * Create an
     *Executor that uses a single worker thread to run the thread in an unbounded queue. (Note that if this single thread is terminated due to a failure during execution before shutdown,
     * then a new thread will perform subsequent tasks in its place if needed). Tasks are guaranteed to be executed sequentially and no more than one thread will be active at any given time. Unlike the other equivalent
     * newFixedThreadPool(1) , the executor returned by this method is guaranteed to use additional threads without reconfiguring.
     *
     * @return
     */
    public ExecutorService createSingleThreadExecutor() {
        // Create
        executors = Executors.newSingleThreadExecutor(getThreadFactory());
        return executors;
    }
   
    /**
     * Create a
     *Executor that uses a single worker thread to run the thread in an unbounded queue. (Note that if this single thread is terminated due to a failure during execution before shutdown,
     * then a new thread will perform subsequent tasks in its place if needed). Tasks are guaranteed to be executed sequentially, and no more than one thread will be active at any given time. Unlike the other equivalent
     * newFixedThreadPool(1) , the executor returned by this method is guaranteed to use additional threads without reconfiguring.
     *
     * @return
     */
    public ExecutorService createNewScheduledThreadPool (int size) {
        // create
        executors = Executors.newScheduledThreadPool(size,getThreadFactory());
        return executors;
    }

    /**
     * Create a thread pool that can create new threads as needed, but reuse previously constructed threads as they become available. For programs that perform many short-lived asynchronous tasks, these thread pools often improve program performance. Calling
     *execute will reuse a previously constructed thread (if thread is available). If no existing thread is available, a new thread is created and added to the pool. Terminate and remove from the cache those
     threads that have not been used for 60 * seconds. Therefore, thread pools that remain idle for a long time do not use any resources. Note that it is possible to use the ThreadPoolExecutor
     * constructors to create thread pools with similar properties but different details (such as timeout parameters).
     *
     * @return
     */
    public ExecutorService createCachedThreadPool() {
        // Create
        executors = Executors.newCachedThreadPool(getThreadFactory());
        return executors;
    }

    /**
     * Create a reusable thread pool with a fixed number of threads to share an unbounded queue way to run these threads. At any point, most of the nThreads
     * threads will be active processing tasks. If submitting additional tasks while all threads are active
     * , the additional task will wait in the queue until a thread becomes available. If any thread terminates due to a failure
     * during execution before shutdown, a new thread will perform subsequent tasks in its place (if needed). Threads in the pool will persist until a thread is explicitly shut down.
     *
     * @return
     */
    public ExecutorService createFixedThreadPool(int size) {
        // Create
        executors = Executors.newFixedThreadPool(size, getThreadFactory());
        return executors;
    }


    /**
     * Get thread pool factory
     *
     * @return
     */
    private ThreadFactory getThreadFactory() {
        return new ThreadFactory() {
            AtomicInteger sn = new AtomicInteger();
            public Thread newThread(Runnable r) {
                SecurityManager s = System.getSecurityManager();
                ThreadGroup group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
                Thread t = new Thread(group, r);
                t.setName("任务线程 - " + sn.incrementAndGet());
                return t;
            }
        };
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326286218&siteId=291194637