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();
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者