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();
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。