Java中怎么使用Executor接口

发布时间:2021-06-21 18:11:02 作者:Leah
来源:亿速云 阅读:176

这篇文章将为大家详细讲解有关Java中怎么使用Executor接口,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

一、Executor接口的理解

二、Executor接口的类图结构

Java中怎么使用Executor接口

由类图结构可知:

三、Executor接口中常用的方法

void execute(Runnable command) 在将来的某个时间执行给定的命令。 该命令可以在一个新线程,一个合并的线程中或在调用线程中执行,由Executor实现。

四、线程池的创建分为两种方式(主要介绍通过ThreadPoolExecutor方式)

注:通过Executors类的方式创建线程池,参考lz此博文链接https://www.yisu.com/article/215163.htm

1.ThreadPoolExecutor类中的构造方法

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue workQueue,defaultHandler)

2、 ThreadPoolExecutor类中构造函数的参数解析

3、ThreadPoolExecutor类创建线程池示例

代码

package com.xz.thread.executor;

import java.util.concurrent.*;


public class Demo {
    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(3,3,
                1L, TimeUnit.MINUTES,new LinkedBlockingDeque<>());
        for(int i=1;i<=5;i++){
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                    try {
                        Thread.sleep(1000);
                        System.out.println("睡眠一秒钟");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

输出结果如下图

Java中怎么使用Executor接口

结论:无论是创建何种类型线程池(newFixedThreadPool、newSingleThreadExecutor、newCachedThreadPool等等),均会调用ThreadPoolExecutor构造函数。

Java中怎么使用Executor接口
Java中怎么使用Executor接口

关于Java中怎么使用Executor接口就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. executor启动task
  2. Java中怎么使用Executor框架

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java executor

上一篇:SpringBoot中自动配置异常处理的原理是什么

下一篇:DEBUG方式线程的底层运行原理是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》