Java Lambda表达式 常用工具类

2023-05-16

Runnable

public static void main(String[] args)
{
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(() ->
    {
        Thread.currentThread().setName("I am child thread");
        try
        {
            Thread.sleep(2);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ", id: " + Thread.currentThread().getId());
    });
}

Callable

public static void main(String[] args)
{
    ExecutorService executorService = Executors.newCachedThreadPool();
    Future<Double> future = executorService.submit(() ->
    {
        Thread.currentThread().setName("I am child thread.");
        System.out.println(Thread.currentThread().getName() + ", id: " + Thread.currentThread().getId());
        Random random = new Random();
        Double weight = random.nextDouble();
        System.out.println("weight: " + weight);
        return weight;
    });
    executorService.shutdown();

    try
    {
        Double result = future.get(1, TimeUnit.SECONDS);
        System.out.println("Result: " + result);
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }
    catch (ExecutionException e)
    {
        e.printStackTrace();
    }
    catch (TimeoutException e)
    {
        e.printStackTrace();
    }
}

FutrueTask

public static void main(String[] args)
{
    ExecutorService executorService = Executors.newCachedThreadPool();

    FutureTask<Double> futureTask = new FutureTask<Double>(() ->
    {
        Thread.currentThread().setName("I am child thread.");
        System.out.println(Thread.currentThread().getName() + ", id: " + Thread.currentThread().getId());
        Random random = new Random();
        Double weight = random.nextDouble();
        System.out.println("weight: " + weight);
        return weight;
    });

    executorService.submit(futureTask);
    executorService.shutdown();

    try
    {
        Double result = futureTask.get(2, TimeUnit.SECONDS);
        System.out.println("Result: " + result);
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }
    catch (ExecutionException e)
    {
        e.printStackTrace();
    }
    catch (TimeoutException e)
    {
        e.printStackTrace();
    }
}

CompletableFutrue

public class CompletableFutrueTest
{
    public static void main(String[] args)
    {
        try
        {
//			CompletableFutrueTest.runAync();
//			CompletableFutrueTest.supplyAsync();
//          CompletableFutrueTest.whenComplete();
//            CompletableFutrueTest.thenApply();
//            CompletableFutrueTest.handle();
            CompletableFutrueTest.thenAccept();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    //无返回值
    private static void runAync() throws Exception
    {
        CompletableFuture future = CompletableFuture.runAsync(() ->
        {
            try
            {
                TimeUnit.SECONDS.sleep(1);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("run end...");
        });
        future.get();
    }

    //有返回值
    private static void supplyAsync() throws Exception
    {
        CompletableFuture<Long> future = CompletableFuture.supplyAsync(() ->
        {
            try
            {
                TimeUnit.SECONDS.sleep(1);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("run end ...");
            return System.currentTimeMillis();
        });

        long time = future.get();
        System.out.println("time: " + time);
    }

    //计算结果完成时的回调方法
    private static void whenComplete() throws Exception
    {
        //链式编程简洁
        //创建一个异步操作
        CompletableFuture.runAsync(() ->
        {
            try
            {
                TimeUnit.SECONDS.sleep(1);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            if (new Random().nextInt(10) % 2 == 0)
            {
                int i = 12 / 0;
            }
            System.out.println("run end ...");

        }).exceptionally((throwable) ->
        {
            System.out.println("执行失败! " + throwable.getMessage());
            return null;
        }).whenComplete((aVoid, throwable) ->
        {
            System.out.println("执行完毕");
        });

        TimeUnit.SECONDS.sleep(2);
    }

    //当一个线程依赖另一个线程
    private static void thenApply() throws Exception
    {
        CompletableFuture future = CompletableFuture.supplyAsync(() ->
        {
            long result = new Random().nextInt(100);
            System.out.println("result1=" + result);
            return result;
        }).thenApply(t ->
        {
            long result = t * 5;
            System.out.println("result2=" + result);
            return result;
        });

        long result = (long) future.get();
        System.out.println(result);
    }

    //执行任务完成时对结果的处理
    //handle 方法和 thenApply 方法处理方式基本一样。
    //不同的是 handle 是在任务完成后再执行,还可以处理异常的任务。
    //thenApply 只可以执行正常的任务,任务出现异常则不执行 thenApply 方法。
    private static void handle() throws Exception
    {
        CompletableFuture future = CompletableFuture.supplyAsync(() ->
        {
            int i = 10 / 0;
            return new Random().nextInt(100);
        }).handle((param, throwable) ->
        {
            int result = -1;
            if (null == throwable)
            {
                result = param * 5;
            }
            else
            {
                System.out.println("error: " + throwable.getMessage());
            }
            return result;
        });
        System.out.println(future.get());
    }

    //接收任务的处理结果,并消费处理,无返回结果。
    private static void thenAccept() throws Exception
    {
        CompletableFuture future = CompletableFuture.supplyAsync(() ->
        {
            return new Random().nextInt(100);
        }).thenAccept((param ->
        {
            System.out.println("result: " + param);
        }));

        future.get();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java Lambda表达式 常用工具类 的相关文章

  • matlab使用app designer进行界面开发时,给控件的显示值进行赋值时,提示‘Text‘ 或‘Value‘ 必须为字符向量或字符串标量的解决办法

    使用 xff1a sprintf 39 s 39 taskID 进行变量值的格式化 如下图 xff1a 以及 xff1a
  • Chrome安装zotero connector 插件

    1 下载zotero connector插件 ZoteroConnectorv5 0 68 zip 其它文档类资源 CSDN下载 2 找到crx文件 xff0c 重命名为rar然后解压 3 打开扩展应用安装界面 4 打开开发者模式 xff0
  • UnBBayes考虑时序因素时的推理

    最近在使用UnBBayes进行MEBN的研究 xff0c 有时候推理需要考虑上一时刻的状态 一开始总是无法产生前一时刻状态的节点 当加入证据 t pre 61 pretimeOf t now 后就可以正常出现上一时刻的状态的节点了
  • zotero文献管理软件插件配置终极教程

    zotero是一款开源免费的文献管理工具 xff0c 在各位大神制作的插件加持下 xff0c 对于我来说已经没有满足不了的文献管理需求了 xff01 xff01 xff01 现将zotero使用教程整理如下 首先感谢贡献zotero和zot
  • ROS多机器人时rviz无法显示机器人模型,提示:param robot_description not found by searchParam()

    如图所示 xff0c 使用ROS进行多机器人仿真时 xff0c RobotModel无法显示机器人模型 xff0c 提示 xff1a param robot description not found by searchParam 原因 x
  • xcode使用gdal库

    GDAL Geospatial Data Abstraction Library 是一个在X MIT许可协议下的开源栅格空间数据转换库 它利用抽象数据模型来表达所支持的各种文件格式 它还有一系列命令行工具来进行数据转换和处理 GDAL提供对
  • VS2017#include "xxx.h"

    在学习使用vs编辑C 43 43 代码 xff0c 目前需要 记录下如何 include myHeaders h span class hljs keyword span span class hljs comment include my
  • MAC系统版本AnyLogic提示the font “Times“ is not available

    问题原因 xff1a MAC新版本系统中移除了Times字体 导致JAVA运行出现问题 如图所示为需要安装的Times字体 解决方法 xff1a 重新安装TImes字体 下载地址
  • LIBTIFF读取tiff文件时,打印buf出错

    如图所示 xff0c 按照官网提供的例程读取tiff文件 xff0c 并打印读取的值时 xff0c 提示 xff1a Subscript of pointer to incomplete type 39 void 39 代码如下 xff1a
  • 使用css选择器获取元素

  • udp如何实现可靠性传输?

    1udp与tcp的区别 TCP xff08 TransmissionControl Protocol 传输控制协议 xff09 是一种面向连接的 可靠的 基于字节流的传输层通信协议 UDP是User Datagram Protocol xf
  • SpringMVC项目中的常用配置

    在SpringMVC项目环境中 xff0c 经常需要配置一些信息 xff0c 包括 xff1a 前端控制器 xff08 DispatcherServlet xff09 处理器映射器 xff08 HandlerMapping xff09 处理
  • PHP 常见错误及其解决方法

    PHP是一种广泛应用于Web开发的编程语言 xff0c 由于其易学易用的特点 xff0c 越来越多的开发者开始使用PHP进行开发工作 然而 xff0c 在PHP开发过程中 xff0c 可能会出现各种错误 xff0c 导致程序无法正常运行 本
  • ubuntu22.04设置开启自启动命令脚本

    前言 xff1a 是这样的 xff0c 新的机器要挂在nfs存储 xff0c 报错 xff1a root 64 85 document mount t nfs o nolock 192 168 1 xx disk xiao home xia
  • 思考练习题

    1 循环求和 xff1a 利用循环语句计算从100加到500的整数的总和 public static void main String args int sum 61 0 for int i 61 100 i lt 61 500 i 43
  • 七步搞定CentOS6.8内核升级和Docker的安装

    博主秋招提前批已拿百度 字节跳动 拼多多 顺丰等公司的offer xff0c 可加微信 xff1a pcwl Java 一起交流秋招面试经验 xff0c 可获得博主的秋招简历和复习笔记 一 内核的升级 最近安装需要在虚拟机Linux系统上安
  • 天干地支算法

    天干地支算法 首先我们需要知道什么是天干什么是地支 xff0c 有多少个天干多少个地支 xff1f 天干 Celestial Stem 中国古代的一种文字计序符号 xff0c 共10个字 甲 乙 丙 丁 戊 己 庚 辛 壬 癸 xff0c
  • 面对突发流量,保证服务可用的4个手段

    前言 不知道你有没有这样的经历 xff0c 线上的系统突然来了很大的流量 xff0c 有可能是黑客的攻击 xff0c 也有可能是业务量远远大于你的预估 xff0c 如果你的系统没有做任何的防护措施 xff0c 这时候系统负载过高 xff0c
  • 【MongoDB】二、MongoDB数据库的基本操作

    MongoDB 二 MongoDB数据库的基本操作 实验目的实验内容任务一 xff1a xff08 1 xff09 创建数据库newdb xff08 2 xff09 在数据库newdb中创建集合mycollection xff08 3 xf
  • OC中的MRC内存管理方式

    MRC内存管理 xff1a Manual Reference Counting 一 人工引用计数 xff1a 内存的开辟和释放都由程序代码进 行控制 相对垃圾回收来说 对内存的控制更加灵活 可以在需要释放的时候及时释放 对程序员的要求较 高

随机推荐