/** * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue. At any point, at most * <tt>nThreads</tt> threads will be active processing tasks. * If additional tasks are submitted when all threads are active, * they will wait in the queue until a thread is available. * If any thread terminates due to a failure during execution * prior to shutdown, a new one will take its place if needed to * execute subsequent tasks. The threads in the pool will exist * until it is explicitly {@link ExecutorService#shutdown shutdown}. * * @param nThreads the number of threads in the pool * @return the newly created thread pool * @throws IllegalArgumentException if <tt>nThreads <= 0</tt> */ publicstatic ExecutorService newFixedThreadPool(int nThreads){ returnnew ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
/** * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue, using the provided * ThreadFactory to create new threads when needed. At any point, * at most <tt>nThreads</tt> threads will be active processing * tasks. If additional tasks are submitted when all threads are * active, they will wait in the queue until a thread is * available. If any thread terminates due to a failure during * execution prior to shutdown, a new one will take its place if * needed to execute subsequent tasks. The threads in the pool will * exist until it is explicitly {@link ExecutorService#shutdown * shutdown}. * * @param nThreads the number of threads in the pool * @param threadFactory the factory to use when creating new threads * @return the newly created thread pool * @throws NullPointerException if threadFactory is null * @throws IllegalArgumentException if <tt>nThreads <= 0</tt> */ publicstatic ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory){ returnnew ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); }
除了能定制ThreadFactory之外,和上个方法一样。
Executors#newSingleThreadExecutor()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/** * Creates an Executor that uses a single worker thread operating * off an unbounded queue. (Note however that if this single * thread terminates due to a failure during execution prior to * shutdown, a new one will take its place if needed to execute * subsequent tasks.) Tasks are guaranteed to execute * sequentially, and no more than one task will be active at any * given time. Unlike the otherwise equivalent * <tt>newFixedThreadPool(1)</tt> the returned executor is * guaranteed not to be reconfigurable to use additional threads. * * @return the newly created single-threaded Executor */ publicstatic ExecutorService newSingleThreadExecutor(){ returnnew FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
/** * Creates a thread pool that creates new threads as needed, but * will reuse previously constructed threads when they are * available. These pools will typically improve the performance * of programs that execute many short-lived asynchronous tasks. * Calls to <tt>execute</tt> will reuse previously constructed * threads if available. If no existing thread is available, a new * thread will be created and added to the pool. Threads that have * not been used for sixty seconds are terminated and removed from * the cache. Thus, a pool that remains idle for long enough will * not consume any resources. Note that pools with similar * properties but different details (for example, timeout parameters) * may be created using {@link ThreadPoolExecutor} constructors. * * @return the newly created thread pool */ publicstatic ExecutorService newCachedThreadPool(){ returnnew ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
/** * Returns an object that delegates all defined {@link * ExecutorService} methods to the given executor, but not any * other methods that might otherwise be accessible using * casts. This provides a way to safely "freeze" configuration and * disallow tuning of a given concrete implementation. * @param executor the underlying implementation * @return an <tt>ExecutorService</tt> instance * @throws NullPointerException if executor null */ publicstatic ExecutorService unconfigurableExecutorService(ExecutorService executor){ if (executor == null) thrownew NullPointerException(); returnnew DelegatedExecutorService(executor); }
/** * Creates a thread pool that can schedule commands to run after a * given delay, or to execute periodically. * @param corePoolSize the number of threads to keep in the pool, * even if they are idle. * @return a newly created scheduled thread pool * @throws IllegalArgumentException if <tt>corePoolSize < 0</tt> */ publicstatic ScheduledExecutorService newScheduledThreadPool(int corePoolSize){ returnnew ScheduledThreadPoolExecutor(corePoolSize); }
/** * Creates a thread pool that can schedule commands to run after a * given delay, or to execute periodically. * @param corePoolSize the number of threads to keep in the pool, * even if they are idle. * @param threadFactory the factory to use when the executor * creates a new thread. * @return a newly created scheduled thread pool * @throws IllegalArgumentException if <tt>corePoolSize < 0</tt> * @throws NullPointerException if threadFactory is null */ publicstatic ScheduledExecutorService newScheduledThreadPool( int corePoolSize, ThreadFactory threadFactory){ returnnew ScheduledThreadPoolExecutor(corePoolSize, threadFactory); }
/** * Creates a single-threaded executor that can schedule commands * to run after a given delay, or to execute periodically. * (Note however that if this single * thread terminates due to a failure during execution prior to * shutdown, a new one will take its place if needed to execute * subsequent tasks.) Tasks are guaranteed to execute * sequentially, and no more than one task will be active at any * given time. Unlike the otherwise equivalent * <tt>newScheduledThreadPool(1)</tt> the returned executor is * guaranteed not to be reconfigurable to use additional threads. * @return the newly created scheduled executor */ publicstatic ScheduledExecutorService newSingleThreadScheduledExecutor(){ returnnew DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1)); }
/** * Creates a single-threaded executor that can schedule commands * to run after a given delay, or to execute periodically. (Note * however that if this single thread terminates due to a failure * during execution prior to shutdown, a new one will take its * place if needed to execute subsequent tasks.) Tasks are * guaranteed to execute sequentially, and no more than one task * will be active at any given time. Unlike the otherwise * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt> * the returned executor is guaranteed not to be reconfigurable to * use additional threads. * @param threadFactory the factory to use when creating new * threads * @return a newly created scheduled executor * @throws NullPointerException if threadFactory is null */ publicstatic ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory){ returnnew DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1, threadFactory)); }
new ScheduledThreadPoolExecutor(1)进行DelegatedScheduledExecutorService包装。
/** * Returns an object that delegates all defined {@link * ScheduledExecutorService} methods to the given executor, but * not any other methods that might otherwise be accessible using * casts. This provides a way to safely "freeze" configuration and * disallow tuning of a given concrete implementation. * @param executor the underlying implementation * @return a <tt>ScheduledExecutorService</tt> instance * @throws NullPointerException if executor null */ publicstatic ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor){ if (executor == null) thrownew NullPointerException(); returnnew DelegatedScheduledExecutorService(executor); }
/** * The default thread factory */ staticclassDefaultThreadFactoryimplementsThreadFactory{ staticfinal AtomicInteger poolNumber = new AtomicInteger(1); final ThreadGroup group; final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix;
DefaultThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s != null)? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; }
public Thread newThread(Runnable r){ Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } }
/** * Returns a {@link Callable} object that, when * called, runs the given task and returns the given result. This * can be useful when applying methods requiring a * <tt>Callable</tt> to an otherwise resultless action. * @param task the task to run * @param result the result to return * @return a callable object * @throws NullPointerException if task null */ publicstatic <T> Callable<T> callable(Runnable task, T result){ if (task == null) thrownew NullPointerException(); returnnew RunnableAdapter<T>(task, result); }
/** * Returns a {@link Callable} object that, when * called, runs the given task and returns <tt>null</tt>. * @param task the task to run * @return a callable object * @throws NullPointerException if task null */ publicstatic Callable<Object> callable(Runnable task){ if (task == null) thrownew NullPointerException(); returnnew RunnableAdapter<Object>(task, null); }
/** * Returns a {@link Callable} object that, when * called, runs the given privileged action and returns its result. * @param action the privileged action to run * @return a callable object * @throws NullPointerException if action null */ publicstatic Callable<Object> callable(final PrivilegedAction<?> action){ if (action == null) thrownew NullPointerException(); returnnew Callable<Object>() { public Object call(){ return action.run(); }}; }
/** * Returns a {@link Callable} object that, when * called, runs the given privileged exception action and returns * its result. * @param action the privileged exception action to run * @return a callable object * @throws NullPointerException if action null */ publicstatic Callable<Object> callable(final PrivilegedExceptionAction<?> action){ if (action == null) thrownew NullPointerException(); returnnew Callable<Object>() { public Object call()throws Exception { return action.run(); }}; }
/** * Returns a {@link Callable} object that will, when * called, execute the given <tt>callable</tt> under the current * access control context. This method should normally be * invoked within an {@link AccessController#doPrivileged} action * to create callables that will, if possible, execute under the * selected permission settings holding within that action; or if * not possible, throw an associated {@link * AccessControlException}. * @param callable the underlying task * @return a callable object * @throws NullPointerException if callable null * */ publicstatic <T> Callable<T> privilegedCallable(Callable<T> callable){ if (callable == null) thrownew NullPointerException(); returnnew PrivilegedCallable<T>(callable); }
/** * Returns a {@link Callable} object that will, when * called, execute the given <tt>callable</tt> under the current * access control context, with the current context class loader * as the context class loader. This method should normally be * invoked within an {@link AccessController#doPrivileged} action * to create callables that will, if possible, execute under the * selected permission settings holding within that action; or if * not possible, throw an associated {@link * AccessControlException}. * @param callable the underlying task * * @return a callable object * @throws NullPointerException if callable null * @throws AccessControlException if the current access control * context does not have permission to both set and get context * class loader. */ publicstatic <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable){ if (callable == null) thrownew NullPointerException(); returnnew PrivilegedCallableUsingCurrentClassLoader<T>(callable); }
/** * A callable that runs given task and returns given result */ staticfinalclassRunnableAdapter<T> implementsCallable<T> { final Runnable task; final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call(){ task.run(); return result; } }