Introduction and use of java thread pool (Executor framework)

1. First look at the classes that make up

 

 

 

public  interface the Executor {    // top-level interface Executor, the method defines a thread of execution

     void Execute (the Runnable Command);
}
public  interface ExecutorService the extends Executor {
 
  // define the methods associated thread pool cycle
void the shutdown (); // gentle off: no longer accept new tasks while waiting for the completion of tasks that have been submitted (including the execution of the task has not yet started ) List <Runnable> shutdownNow ();  // close the brutal attempt to cancel the task being performed, while no longer continue to perform the task but did not submit the beginning of boolean isShutdown (); // Check whether the actuator is closed boolean isTerminated ();    // query whether to terminate the thread pool boolean awaitTermination ( Long timeout, TimeUnit Unit) // wait for the thread pool reaches the final state, usually call this method after shutdown () closed the thread pool to achieve synchronization effect throws InterruptedException; <T> Future <T > Submit (a Callable <T> task); // Submit () method is used to submit the task with a return value of <T> Future <T> Submit (the Runnable task, Result T); Future ? <> Submit (the Runnable task) ; <T> List <Future <T >>invokeAll(Collection<? the extends a Callable <T >> Tasks) // for complex task submitted throws InterruptedException; <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException; <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException; <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }

2. ThreadPoolExecutor for the realization of a thread pool

public ThreadPoolExecutor ( int corePoolSize,       the number // number of kernel threads, thread pool to maintain representatives in the idle state of the thread
                               int maximumPoolSize,   // the thread pool that the maximum permissible number of threads
                               Long keepAliveTime,  // survival time of idle threads 
                              TimeUnit unit,    // time unit 
                              BlockingQueue <Runnable> workQueue,   // used to temporarily store queue tasks 
                              ThreadFactory threadFactory,      // used to create threads 
                              RejectedExecutionHandler Handler) {   // deny policy, the task can not be added to the queue is to play a role
        
    }

3. Deny Policy

  (1) AbortPolicy: This strategy throws RejectedExecutionException, the caller is processed after catching exceptions.

  (2) DiscartPolicy: When a new task is not added to the queue, the policy quietly abandon the task.

  (3) DiscardOldestPolicy: This policy is about to abandon the task to be performed.

  (4) CallerRunsPolicy: This policy will fall back to the caller certain tasks.

4. The four types of thread pools (general method are defined in the thread pool class Executors)

  Complete the process of submitting tasks when all the parameters of the thread pool valid settings: View the current number of threads is greater than corePoolSize, if less than create a new thread to perform the task, or to join the mission to workQueue; if workerQueue was full, then the view is less than the number of threads maximumPoolSize, if less than create a new thread to execute, otherwise abandon the policy. In addition, if the thread idle time is greater than keepAliveTime, then destroy threads.

 public the ThreadPoolExecutor ( int corePoolSize,             // General constructor
                               int maximumPoolSize,
                               Long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory (), defaultHandler);      // use the default thread factory and default deny policy 
    }

private static final RejectedExecutionHandler defaultHandler =        //默认为AbortPolicy
new AbortPolicy();
 

  (1) newFixedThreadPool: to create a fixed-size thread pool

public  static ExecutorService newFixedThreadPool ( int nThreads) {  
         return  new new the ThreadPoolExecutor (nThreads, nThreads,        // = the maximum number of the number of cores, keepAliveTime = 0 (if no other than the thread will always exist), workQueue using a LinkedBlockingQueue
                                       0L , TimeUnit.MILLISECONDS,
                                       new new a LinkedBlockingQueue < the Runnable> ());  
    }

ExecutorService newFixedThreadPool static public (int nThreads, a ThreadFactory threadFactory) {   // another configuration method, the plant may be specified thread
return the ThreadPoolExecutor new new (nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new new a LinkedBlockingQueue <the Runnable> (),
threadFactory);
}
 
 

  (2) newCachedThreadPool: more needs to create a thread pool

public  static ExecutorService newCachedThreadPool () {
         return  new new the ThreadPoolExecutor (0 , Integer.MAX_VALUE,    // core size = 0, the maximum number is not limited to, survival time was 60s (if there is no job for a long time the thread pool is empty), used as SynchronousQueue workeQueue
                                       60L , TimeUnit.SECONDS,
                                       new new SynchronousQueue <the Runnable> ());
    }

  (3) newScheduledThreadPool: create a thread pool may delay the execution of tasks

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
 public a ScheduledThreadPoolExecutor ( int corePoolSize) {
         Super (corePoolSize, Integer.MAX_VALUE, 0 , nanoseconds,   // specify the size of the core, not the maximum number of threads does not expire, as used DelayedWordeQueue workeQueue
               new new DelayedWorkQueue ());
    }

  (4) newSingleThreadPool: only one thread to create a thread pool

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService  
            ( New new the ThreadPoolExecutor (1, 1 ,         // number of cores and the maximum number is 1, the survival time is not limited, as used LinkedBlockingQueue workQueue
                                     0L , TimeUnit.MILLISECONDS,
                                     new new LinkedBlockingQueue <the Runnable> ()));
    }

 

 

Guess you like

Origin www.cnblogs.com/liwangcai/p/11884690.html