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); } } }
相关文章推荐
- java&android线程池-Executor框架之ThreadPoolExcutor&ScheduledThreadPoolExecutor浅析(多线程编程之三)
- Java&Android的线程池ExecutorService
- 【转】java&android线程池-Executor框架之ThreadPoolExcutor&ScheduledThreadPoolExecutor浅析(多线程编程之三)
- Java&Android的线程池---ExecutorService
- java&android线程池-Executor框架之ThreadPoolExcutor&ScheduledThreadPoolExecutor浅析(多线程编程之三)
- Java&Android的线程池---ExecutorService
- [Android] "Failed to find Java version for 'C:\Windows\system32\java.exe"问题的解决方法
- [异常-开发环境-myeclipse-ubuntu-android2.2]keytool": java.io.IOException: error=13, 权限不够
- 【066】Android & Java 难点解析
- android java.net.UnknownHostException: Unable to resolve host "...": No address associated 错误
- JAVA&Android: 如何显示比当前DATE时间,提前一个月的时间
- Java多线程编程--(8)学习Java5.0 并发编程包--线程池、Callable & Future 简介
- Android问题:Test run failed: Instrumentation run failed due to 'java.lang.RuntimeException'
- 多线程并发库高级应用 之 java5中的线程并发库--线程池、Callable&Future
- Java & Android 多线程
- 多线程并发库高级应用 之 java5中的线程并发库--线程池、Callable&Future
- java.lang.IllegalStateException: ActionBarContextView can only be used with android:layout_width="
- android Collections.sort(List<T> list) 与JAVA Collections.sort(List<T> list)
- java->android->java
- Warning: Error parsing 'C:\android-sdk-windows\platforms\android-2\sdk.properties': java.io.FileNotF