首页 > 编程语言 >Java新建一个子线程异步运行方法

Java新建一个子线程异步运行方法

时间:2024-02-07 09:23:28浏览次数:36  
标签:异步 Java private threadPool 线程 new static ThreadPoolExecutor

如何在运行主方法的同时异步运行另一个方法,我是用来更新缓存;

1. 工具类

public class ThreadPoolUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolUtils.class);
    private static final String POOL_NAME = "thread-im-runner";
    // 等待队列长度
    private static final int BLOCKING_QUEUE_LENGTH = 20000;
    // 闲置线程存活时间
    private static final int KEEP_ALIVE_TIME = 5 * 1000;
    private static ThreadPoolExecutor threadPool = null;

    private ThreadPoolUtils() {
        throw new IllegalStateException("utility class");
    }

    /**
     * 无返回值直接执行
     *
     * @param runnable 需要运行的任务
     */
    public static void execute(Runnable runnable) {
        getThreadPool().execute(runnable);
    }

    /**
     * 有返回值执行 主线程中使用Future.get()获取返回值时,会阻塞主线程,直到任务执行完毕
     *
     * @param callable 需要运行的任务
     */
    public static <T> Future<T> submit(Callable<T> callable) {
        return getThreadPool().submit(callable);
    }

    private static synchronized ThreadPoolExecutor getThreadPool() {
        if (threadPool == null) {
            // 核心线程数、最大线程数、闲置线程存活时间、时间单位、线程队列、线程工厂、当前线程数已经超过最大线程数时的异常处理策略
            threadPool = new ThreadPoolExecutor(50, 500, KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(BLOCKING_QUEUE_LENGTH),
                new ThreadFactoryBuilder().setNameFormat(POOL_NAME + "-%d").build(),
                new ThreadPoolExecutor.AbortPolicy() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                        LOGGER.warn("线程过多,当前运行线程总数:{},活动线程数:{}。等待队列已满,等待运行任务数:{}", e.getPoolSize(), e.getActiveCount(),
                            e.getQueue().size());
                    }
                });
        }
        return threadPool;
    }

    private static synchronized ThreadPoolExecutor getThreadPoolByCpuNum() {
        if (threadPool == null) {
            // 获取处理器数量
            int cpuNum = Runtime.getRuntime().availableProcessors();
            // 根据cpu数量,计算出合理的线程并发数
            int maximumPoolSize = cpuNum * 2 + 1;
            // 核心线程数、最大线程数、闲置线程存活时间、时间单位、线程队列、线程工厂、当前线程数已经超过最大线程数时的异常处理策略
            threadPool = new ThreadPoolExecutor(maximumPoolSize - 1, maximumPoolSize, KEEP_ALIVE_TIME,
                TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(BLOCKING_QUEUE_LENGTH),
                new ThreadFactoryBuilder().setNameFormat(POOL_NAME + "-%d").build(),
                new ThreadPoolExecutor.AbortPolicy() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                        LOGGER.warn("线程爆炸了,当前运行线程总数:{},活动线程数:{}。等待队列已满,等待运行任务数:{}", e.getPoolSize(), e.getActiveCount(),
                            e.getQueue().size());
                    }
                });
        }
        return threadPool;
    }
}

2.实际使用

    ThreadPoolUtils.execute(() -> {
            this.Method();
        });

 

标签:异步,Java,private,threadPool,线程,new,static,ThreadPoolExecutor
From: https://www.cnblogs.com/dawenyang/p/18010584

相关文章

  • lazarus 3.0/fpc3.3.1写线程要注意的事项
    近日和高勇交流中发现,以下代码在delphi能编译及正确执行。procedureTForm1.Button2Click(Sender:TObject);vari:integer;beginTThread.CreateAnonymousThread(procedurebeginsleep(3000);TThread.Synchronize(TThread.CurrentThread,proced......
  • 【JAVA】JavaSEの歴史(1.6~17)
    Start ■Jdk1.6〜8、追加のクラス又は新しい機能(1)Lambda//JDK1.6newThread(newRunnable(){publicvoidrun(){System.out.println("Hello,World!");}}).start();//JDK8newThread(()->System.out.println("Hello,World!"))......
  • 【JAVA】JDK8~17の新しい機能の紹介
    JDK8(2014年发布):Lambda表达式:允许在Java中使用函数式编程风格,简化代码并提高可读性。StreamAPI:提供了一种新的数据处理方式,支持函数式编程和并行处理。接口的默认方法和静态方法:允许在接口中定义具有实现的方法,提高了接口的灵活性。新的日期和时间API:引入了java.time包,提......
  • Java的软引用、弱引用和强引用学习
    一、强引用强引用可以直接访问目标对象,所指向的对象在任何时候都不会被系统回收,JVM宁愿抛出OOM异常也不会回收强引用所指向的对象,但是有可能会导致内存泄漏。packagelearn;/***@authorqx*@date2024/1/5*@des*/publicclassDemo{publicstaticvoidmain(S......
  • Java和JavaScript区别与联系
    区别和联系Java和JavaScript是两种不同的编程语言,尽管它们的名称相似,但它们有着不同的特性、用途和工作环境。以下是对它们之间区别与联系的详细说明:语言类型:Java:Java是一种静态类型的编程语言,意味着在编译时需要声明变量的类型,并且强调面向对象编程。JavaScript:JavaScri......
  • 已解决java.lang.IllegalAccessException异常的正确解决方法,亲测有效!!!
    已解决java.lang.IllegalAccessException异常的正确解决方法,亲测有效!!!文章目录问题分析与报错原因解决思路解决方法总结 ----------------------------------------------------------------------------------------------------------------问题分析与报错原因java.lang.IllegalA......
  • 基于Java+Neo4j开发的知识图谱+全文检索的知识库管理系统(源码分析)
    在数字化高度普及的时代,企事业机关单位在日常工作中会产生大量的文档,例如医院制度汇编,企业知识共享库等。针对这些文档性的东西,手工纸质化去管理是非常消耗工作量的,并且纸质化查阅难,易损耗,所以电子化管理显得尤为重要。【springboot+elasticsearch+neo4j+vue+activiti】实现数字......
  • Java之UDP,TCP的详细解析
     练习四:文件名重复publicclassUUIDTest{publicstaticvoidmain(String[]args){Stringstr=UUID.randomUUID().toString().replace("-","");System.out.println(str);//9f15b8c356c54f55bfcb0ee3023fce8a}}```publicclassClient{public......
  • java基础语法之匿名内部类的优化格式lambda
    一:lambda表达式的概述lambda表达式实质上就是对匿内部类的优化但是又不同于匿名内部类。它的使用前提是有且仅有一个抽象方法,有一个接口。二:具体说明<1>函数式编程思想的介绍在数学中,函数就是有输入量、输出量的一套计算方案,也就是“拿数据做操作”在数学中,函数就是有输......
  • Java 数学运算与条件语句全解析
    JavaMathJava的Math类拥有许多方法,允许您在数字上执行数学任务。常用方法:Math.max(x,y):找到x和y的最大值Math.min(x,y):找到x和y的最小值Math.sqrt(x):返回x的平方根Math.abs(x):返回x的绝对值Math.random():返回一个介于0.0和1.0之间的随机......