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 extends Callable> 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
© 2015 - 2025 Weber Informatics LLC | Privacy Policy