All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.loocme.sys.util.ThreadUtil Maven / Gradle / Ivy

package com.loocme.sys.util;

import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 线程帮助类
 * 
 * @author loocme
 * 
 */
@Slf4j
public class ThreadUtil
{

    public static final int ET_SINGLE = 1;
    public static final int ET_CACHED = 2;
    public static final int ET_FIXED = 3;
    public static final int ET_SCHEDULED = 4;
    public static final int ET_QUEUE = 5;

    private static ThreadUtil util = new ThreadUtil();

    public static ExecutorService newSingleThreadExecutor()
    {
        return util.new ExecutorService(ET_SINGLE);
    }

    public static ExecutorService newCachedThreadPool()
    {
        return util.new ExecutorService(ET_CACHED);
    }

    public static ExecutorService newFixedThreadPool(int poolsize)
    {
        return util.new ExecutorService(ET_FIXED, poolsize);
    }

    public static ScheduledExecutorService newSingleThreadScheduledExecutor()
    {
        return newSingleThreadScheduledExecutor(1);
    }

    public static ScheduledExecutorService newSingleThreadScheduledExecutor(
            int poolsize)
    {
        return util.new ScheduledExecutorService(poolsize);
    }

    public static QueueExecutorService newQueueThreadPool(int poolsize)
    {
        return util.new QueueExecutorService(poolsize);
    }
    
    public static QueueExecutorService newQueueThreadPool(int poolsize, Class clz)
    {
        return util.new QueueExecutorService(poolsize, clz);
    }

    public class ExecutorService
    {
        private int type = -1;
        private java.util.concurrent.ExecutorService service;

        private ExecutorService(int type)
        {
            this.type = type;
            this.initService(0);
        }

        private ExecutorService(int type, int poolsize)
        {
            this.type = type;
            this.initService(poolsize);
        }

        private void initService(int poolsize)
        {
            switch (this.type)
            {
                case ET_SINGLE:
                    this.service = Executors.newSingleThreadExecutor();
                    break;
                case ET_CACHED:
                    this.service = Executors.newCachedThreadPool();
                    break;
                case ET_FIXED:
                    this.service = Executors.newFixedThreadPool(poolsize);
                    break;
                default:
                    break;
            }
        }

        public void execute(Runnable command)
        {
            this.service.execute(command);
        }

        public boolean isTerminated()
        {
            return this.service.isTerminated();
        }

        public Future submit(Runnable command)
        {
            return this.service.submit(command);
        }

        public void shutdown()
        {
            this.service.shutdown();
        }

        public List shutdownNow()
        {
            return this.service.shutdownNow();
        }

        public  List> invokeAll(
                Collection> tasks)
        {
            try
            {
                return this.service.invokeAll(tasks);
            }
            catch (InterruptedException e)
            {
                log.error("", e);
            }
            return null;
        }

        public  Future submit(Callable task)
        {
            return this.service.submit(task);
        }
    }

    public interface QueueExecutorHandler
    {
        public void run(Object client);
    }

    public class QueueExecutorService
    {
        private java.util.concurrent.ExecutorService service;
        private ArrayBlockingQueue queue;
        private Set runningSet;
        private int poolsize;

        private QueueExecutorService(int poolsize)
        {
            this(poolsize, null);
        }

        private QueueExecutorService(int poolsize, Class clz)
        {
            this.queue = new ArrayBlockingQueue(poolsize);
            this.runningSet = new HashSet<>();
            this.poolsize = poolsize;
            try
            {
                for (int i = 0; i < poolsize; i++)
                {
                    if (null == clz)
                    {
                        this.queue.put(i);
                    }
                    else
                    {
                        this.queue.put(ReflectUtil.newInstance(clz));
                    }
                }
            }
            catch (InterruptedException e)
            {
                log.error("", e);
            }
            this.service = Executors.newFixedThreadPool(poolsize);
        }

        public void execute(final QueueExecutorHandler handler)
        {
            try
            {
                final Object client = this.queue.take();
                runningSet.add(client);
                this.service.execute(new Runnable() {

                    @Override
                    public void run()
                    {
                        try
                        {
                            handler.run(client);
                        }
                        catch (Exception e)
                        {
                            log.error("线程中execute方法出现异常:", e);
                        }
                        try
                        {
                            runningSet.remove(client);
                            queue.put(client);
                        }
                        catch (InterruptedException e)
                        {
                            log.error("", e);
                        }
                    }
                });
            }
            catch (InterruptedException e)
            {
                log.error("", e);
            }
        }

        public int used()
        {
            return this.poolsize - queue.size();
        }

        public Set usedObjects()
        {
            return this.runningSet;
        }

        public int size()
        {
            return this.poolsize;
        }

        public void shutdownNow()
        {
            try
            {
                this.queue.clear();
                this.service.shutdown();

                if (!this.service.awaitTermination(5, TimeUnit.SECONDS))
                {
                    this.service.shutdownNow();
                }
            }
            catch (InterruptedException e)
            {
                log.error("", e);
                this.service.shutdownNow();
            }
        }
    }

    public class ScheduledExecutorService
    {
        private java.util.concurrent.ScheduledExecutorService service;

        private ScheduledExecutorService(int poolsize)
        {
            if (poolsize > 1)
            {
                this.service = Executors.newScheduledThreadPool(poolsize);
            }
            else
            {
                this.service = Executors.newSingleThreadScheduledExecutor();
            }
        }

        public void schedule(Date date, Runnable command)
        {
            long second = (date.getTime() - new Date().getTime()) / 1000;
            this.service.schedule(command, second, TimeUnit.SECONDS);
        }

        /**
         * @param command
         *            执行的内容
         * @param delay
         *            延迟执行的时间
         * @param unit
         *            延迟执行时间的单位
         */
        public void schedule(Runnable command, long delay, TimeUnit unit)
        {
            this.service.schedule(command, delay, unit);
        }

        /**
         * @param command
         *            执行的内容
         * @param initialDelay
         *            第一次执行前延迟的时间
         * @param period
         *            执行成功之间的时间间隔
         * @param unit
         *            延迟时间和时间价格的单位
         */
        public void scheduleAtFixedRate(Runnable command, long initialDelay,
                long period, TimeUnit unit)
        {
            this.service.scheduleAtFixedRate(command, initialDelay, period,
                    unit);
        }

        /**
         * @param command
         *            执行的内容
         * @param initialDelay
         *            第一次执行前延迟的时间
         * @param delay
         * @param unit
         */
        public void scheduleWithFixedDelay(Runnable command, long initialDelay,
                long delay, TimeUnit unit)
        {
            this.service.scheduleWithFixedDelay(command, initialDelay, delay,
                    unit);
        }

        public boolean isTerminated()
        {
            return this.service.isTerminated();
        }

        public Future submit(Runnable command)
        {
            return this.service.submit(command);
        }

        public void shutdown()
        {
            this.service.shutdown();
        }

        public List shutdownNow()
        {
            return this.service.shutdownNow();
        }
    }
}