美文网首页多线程
Java中的线程池的使用--ThreadPoolExecutor

Java中的线程池的使用--ThreadPoolExecutor

作者: 冰花水焰 | 来源:发表于2020-12-03 16:00 被阅读0次

    ThreadPoolExecutor参数介绍

    1、corePoolSize:核心线程数,核心线程会一直存活,即使没有任务
    2、maximumPoolSize:线程池中的最大线程数
    3、workQueue:阻塞队列的容量,用来存储等待执行的任务
    4、keepAliveTime:线程空闲时间
    5、ThreadFactory:线程工厂
    5、RejectedExecutionHandler:拒绝策略
    6、TimeUnit 时间单位
    

    提交任务的方式

    • execute
    • submit
      两者的区别是execute方法用于提交不需要返回值的任务,submit用于提交需要返回值或者执行状态的任务

    提交任务种类

    1. Runnable
    2. Callable
      区别:Runnable 不会返回结果,并且无法抛出经过检查的异常

    代码实现

    public class ThreadPoolTest {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            //阻塞队列
            BlockingQueue bq = new ArrayBlockingQueue(2);
            //线程工厂
            ThreadFactory factory = new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r);
                }
            };
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2, 60, TimeUnit.SECONDS,bq,factory,new ThreadPoolExecutor.CallerRunsPolicy());
    
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"sss");
                }
            });
            Future<?> ft = threadPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("zhe gai zen me ban");
                    int a = 1;
    
                }
            });
            try{Thread.sleep(100);}catch (Exception e){}
            System.out.println(ft.isDone());
    
            Future<Object> submit = threadPoolExecutor.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return "小猪佩奇";
                }
            });
            try{Thread.sleep(1000);}catch (Exception e){}
            System.out.println(submit.get());
        }
    }
    

    相关文章

      网友评论

        本文标题:Java中的线程池的使用--ThreadPoolExecutor

        本文链接:https://www.haomeiwen.com/subject/jnimwktx.html