美文网首页
ThreadUtils(ExecutorService的包装)

ThreadUtils(ExecutorService的包装)

作者: 大道至简_Andy | 来源:发表于2016-09-21 00:31 被阅读150次

Thread工具类,简单对ExecutorService系列类进行了包装。

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;

public class ThreadUtils
{
    public static ExecutorService newSingleThreadExecutor(String processName)
    {
        return Executors.newSingleThreadExecutor(newThreadFactory(processName));
    }

    public static ExecutorService newFixedThreadPool(int qty, String processName)
    {
        return Executors.newFixedThreadPool(qty, newThreadFactory(processName));
    }

    public static ScheduledExecutorService newSingleThreadScheduledExecutor(String processName)
    {
        return Executors.newSingleThreadScheduledExecutor(newThreadFactory(processName));
    }

    public static ScheduledExecutorService newFixedThreadScheduledPool(int qty, String processName)
    {
        return Executors.newScheduledThreadPool(qty, newThreadFactory(processName));
    }

    public static ThreadFactory newThreadFactory(String processName)
    {
        return newGenericThreadFactory("ProcessName-" + processName);
    }

    public static ThreadFactory newGenericThreadFactory(String processName)
    {
        return new ThreadFactoryBuilder()
            .setNameFormat(processName + "-%d")
            .setDaemon(true)
            .build();
    }

    public static String getProcessName(Class<?> clazz)
    {
        if ( clazz.isAnonymousClass() )
        {
            return getProcessName(clazz.getEnclosingClass());
        }
        return clazz.getSimpleName();
    }
}

相关文章

网友评论

      本文标题:ThreadUtils(ExecutorService的包装)

      本文链接:https://www.haomeiwen.com/subject/hnaoettx.html