1.线程池核心参数

public ThreadPoolExecutor(int corePoolSize,//核心数目
                              int maximumPoolSize,//最大数目
                              long keepAliveTime,//存活时间
                              TimeUnit unit,//存活时间单位
                              BlockingQueue<Runnable> workQueue,//排队队列
                              ThreadFactory threadFactory,//线程工厂
                              RejectedExecutionHandler handler) { //线程满了后,拒绝策略

线程池参数有核心数目,线程最大数目,线程存活时间,排队队列类型
当线程池线程逐渐增加,当线程数目小于等于核心数目时,即使线程完成了任务,也不会被销毁。当线程数目大于核心数目小于最大数目时候,线程完成任务了,多余的线程会存活keepAliveTime长的时间,然后会被销毁,如果线程池线程数目大于最大数目将会进入排队队列中,排队队列有基于数组实现的也有基于链表实现的。当排队队列满了以后,又增加了新的线程,会被抛弃掉,可以配置抛弃策略。

抛弃策略

image.png

A. AbortPolicy: 直接抛出RejectedExecutiongExcepiton异常 A handler for rejected tasks that throws a {@code RejectedExecutionException}. 

B. CallerRunsPolicy: 直接调用线程池执行新创建的线程。 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. 

C. DiscardOldestPolicy: 直接抛弃等待时间最长的,然后执行。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.  

D. DiscardPolicy: 不抛出任何异常,直接抛弃。A handler for rejected tasks that silently discards the rejected task. 

2.创建线程池的几种方式

Executors.newCachedThreadPool();
缓存线程池的核心线程数目为0,也就是说空闲时候,线程会全部销毁,最大线程数目是Integer.MAX_VALUE,排队队列是SynchronousQueue,该队列不保证FIFO,也就是不公平的。

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, 
                                      Integer.MAX_VALUE,
                                      60L,
                                      TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

Executors.newFixedThreadPool(2);

核心线程数目和最大线程数目相等,等待队列为LinkedBlockingQueue,该实现基于链表实现的。创建的线程最大数目为核心线程数目,创建之后不会销毁。

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, 
                                      nThreads,
                                      0L,
                                      TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

Executors.newScheduledThreadPool(2);

该方式创建的线程池能够以一定的延迟或者不同的优先级执行。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {  
    return new ScheduledThreadPoolExecutor(corePoolSize);  
}

Executors.newSingleThreadExecutor();
核心线程数目和最大线程数目同为1,一个线程的线程池。

public static ExecutorService newSingleThreadExecutor() {  
    return new FinalizableDelegatedExecutorService  
        (new ThreadPoolExecutor(1,
                                1,  
                                0L,
                                TimeUnit.MILLISECONDS,  
                                new LinkedBlockingQueue<Runnable>()));  
}

3.线程池使用demo

public class ExcutorPool {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future> futures = new ArrayList();
        for (int i = 1;i<100;i++){
            MyThread myThread = new MyThread("num"+i);
            Future submit = executorService.submit(myThread);
            futures.add(submit);
        }
        int amount = 0;
        for (Future future:futures){
            try {
                Integer result = (Integer) future.get();
                System.out.println(result);
                amount += result;
            }catch (Exception e){

            }
        }
        executorService.shutdown();
        System.out.println("amount:" + amount);
    }
}


class MyThread implements Callable {

    private String myName;

    public MyThread(String myName){
        this.myName = myName;
    }


    @Override
    public Object call() throws Exception {
        try {
            System.out.println(myName +  " start");
            Thread.sleep(1000);
            System.out.println(myName +  " end");
            Random random = new Random();
            return random.nextInt(1000);
        }catch (Exception e){

        }
        return 100;
    }
}

你若安好便是晴天
82 声望10 粉丝

引用和评论

0 条评论