您的位置:首页 > 移动开发 > Android开发

java & android 线程池

2018-03-01 11:02 169 查看

Java 线程池

废话不多,先来一波可以用的工具类,单例写的线程池,具体使用自行参阅~

public class ThreadManager {

private volatile static ThreadManager instance;

private ThreadPoolExecutor poolExecutor;

private LinkedBlockingQueue<Runnable> threadQueue;

private SmartThreadFactory smartThreadFactory;

private SmartRejectHandler smartRejectHandler;

private static final int CORE_SIZE = 10;

private static final int MAXIMUM_POOL_SIZE = Integer.MAX_VALUE;

private static final long KEEP_ALIVE_TIME = 0L;

public static ThreadManager getInstance() {
if (null == instance) {
synchronized (ThreadManager.class) {
if (null == instance) {
instance = new ThreadManager();
}
}
}
return instance;
}

private ThreadManager() {
threadQueue = new LinkedBlockingQueue<>();
smartThreadFactory = new SmartThreadFactory();
smartRejectHandler = new SmartRejectHandler();
poolExecutor = new ThreadPoolExecutor(CORE_SIZE,
MAXIMUM_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.MILLISECONDS,
threadQueue,
smartThreadFactory,
smartRejectHandler);
}

public synchronized void destroy() {
if (poolExecutor != null && !poolExecutor.isShutdown()) {
poolExecutor.shutdown();
}
if (threadQueue != null && threadQueue.size() > 0) {
threadQueue.clear();
}
threadQueue = null;
smartThreadFactory = null;
smartRejectHandler = null;
instance = null;
//Runtime.getRuntime().gc();
}

public boolean executeTaskWithoutException(@Nullable Runnable task, @Nullable String threadName) {
try {
execute(task, threadName);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

/**
* execute task u know
*
* @param task task what u want to execute
* @return if true execute success else failed
*/
public boolean executeTaskWithoutException(@Nullable Runnable task) {
try {
execute(task);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

public Future submitTaskWithoutException(@Nullable Callable task) {
try {
return submit(task);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public Future submitTaskWithoutException(@Nullable Callable task, @Nullable String threadName) {
try {
return submit(task, threadName);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public void executeTask(@Nullable Runnable task, @Nullable String threadName) throws Exception {
execute(task, threadName);
}

public void executeTask(@Nullable Runnable task) throws Exception {
execute(task);
}

public Future sumbitTask(@Nullable Callable task, @Nullable String threadName) throws Exception {
return submit(task, threadName);
}

public Future sumbitTask(@Nullable Callable task) throws Exception {
return submit(task);
}

private void execute(Runnable runnable, String threadName) throws Exception {
smartThreadFactory.setName(threadName);
poolExecutor.execute(runnable);
}

/**
* execute your task u know
*
* @param task task what u want to execute
* @throws Exception RejectedExecutionHandler {@link SmartRejectHandler}
*/
private void execute(Runnable task) throws Exception {
poolExecutor.execute(task);
}

private Future submit(Callable task, String threadName) throws Exception {
smartThreadFactory.setName(threadName);
return poolExecutor.submit(task);
}

/**
* submit task u know
*
* @param task your task
* @return task's result
* @throws Exception RejectedExecutionHandler {@link SmartRejectHandler}
*/
private Future submit(Callable task) throws Exception {
return poolExecutor.submit(task);
}

static class SmartThreadFactory implements ThreadFactory {

private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private String namePrefix;

SmartThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}

public void setName(String name) {
if (!TextUtils.isEmpty(name)) {
namePrefix = name;
}
}

@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement());
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}

static class SmartRejectHandler implements RejectedExecutionHandler {

@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (!executor.isShutdown()) {
executor.execute(r);
} else {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
executor.toString() + "\n pool is shutdown!");
}
}
}
}


关于拒绝策略

虽说大多jdk源码里面就能看到,但是还是为了避免侵权,地址贴上来

java线程池-RejectedExecutionHandler

A handler for tasks that cannot be executed by a ThreadPoolExecutor


意思就是当线程池不能执行该任务是就交由拒绝执行处理器来处理该任务。代码如下:

public interface RejectedExecutionHandler {
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}


我们可以通过下面代码所示的线程池的构造函数来指定线程池的拒绝执行处理器:

public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}

public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}


AbortPolicy

从线程池ThreadPoolExecuto的源码发现它使用的默认策略是:AbortPolicy。该拒绝执行处理器的逻辑如下:

/**
* A handler for rejected tasks that throws a
* {@code RejectedExecutionException}.
*/
public static class AbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public AbortPolicy() { }

/**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}


CallerRunsPolicy

该拒绝执行处理器的逻辑是:用调用线程本身来执行此次提交的任务。

JDK代码如下:

/* Predefined RejectedExecutionHandlers */

/**
* A handler for rejected tasks that runs the rejected task
* directly in the calling thread of the {@code execute} method,
* unless the executor has been shut down, in which case the task
* is discarded.
*/
public static class CallerRunsPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code CallerRunsPolicy}.
*/
public CallerRunsPolicy() { }

/**
* Executes task r in the caller's thread, unless the executor
* has been shut down, in which case the task is discarded.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}


DiscardPolicy

该拒绝执行处理器的逻辑是:静默的丢掉拒绝执行的任务。

JDK 代码如下:

/**
* A handler for rejected tasks that silently discards the
* rejected task.
*/
public static class DiscardPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code DiscardPolicy}.
*/
public DiscardPolicy() { }

/**
* Does nothing, which has the effect of discarding task r.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}


DiscardOldestPolicy

该拒绝执行处理器的逻辑是:丢掉最早提交的任务(马上要被执行的任务),然后重新提交当前要处理的任务。

JDK 代码如下:

/**
* A handler for rejected tasks that discards the oldest unhandled
* request and then retries {@code execute}, unless the executor
* is shut down, in which case the task is discarded.
*/
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code DiscardOldestPolicy} for the given executor.
*/
public DiscardOldestPolicy() { }

/**
* Obtains and ignores the next task that the executor
* would otherwise execute, if one is immediately available,
* and then retries execution of task r, unless the executor
* is shut down, in which case task r is instead discarded.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐