Java 多线程的返回对象和资源独享线程

2023-11-05 15:04

本文主要是介绍Java 多线程的返回对象和资源独享线程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 多线程的返回对象-Future

1.1 Future 

如果你在创建线程时,使用的是 Runnable 接口,那么此时你是无法获取线程执行结果的,如果想要获取线程的执行结果,需要实现 Callable 接口,示例如下:

public class J0_Callable {    static class Task implements Callable<Integer> {        @Override
        public Integer call() throws InterruptedException {
            Thread.sleep(3000);
            return 100;
        }
    }    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executors = Executors.newSingleThreadExecutor();
        Future<Integer> submit = executors.submit(new Task());
        System.out.println("计算结果为:" + submit.get());
        executors.shutdown();
    }
}

此时通过 ExecutorService.submit() 进行提交,得到的是一个 Future 对象,它包含了线程的执行结果,当你调用其 get() 方法时,它会阻塞直至获取到线程的返回结果。

1.2  FutureTask

使用 Callable 接口的限制是:其只能使用线程池提交,而不能使用单独的线程进行提交。如果想要使用单独的线程提交,可以使用 FutureTask 对其进行包装,FutureTask 是 Runnable 接口的实现类,可以用于任何场景下的提交,示例如下:

static class Task implements Callable<Integer> {@Overridepublic Integer call() throws InterruptedException {
        Thread.sleep(3000);return 100;}
}public static void main(String[] args) throws ExecutionException, InterruptedException {
    FutureTask<Integer> futureTask01 = new FutureTask<>(new Task());
    FutureTask<Integer> futureTask02 = new FutureTask<>(new Task());// 使用独立的线程执行new Thread(futureTask01).start();
    ExecutorService executorService = Executors.newSingleThreadExecutor();// 使用线程池提交
    executorService.submit(futureTask02);
    System.out.println("futureTask01 计算结果为:" + futureTask01.get());
    System.out.println("futureTask02 计算结果为:" + futureTask01.get());
    executorService.shutdown();
}

1.3  CompletableFuture

CompletableFuture 是 JDK 8 提供的增强后 Future ,它支持流式调用,等待唤醒等一系列新的功能:

1.3.1 等待唤醒

public class J2_CompletableFuture {static class Compute implements Runnable {private CompletableFuture<Integer> future;Compute(CompletableFuture<Integer> future) {this.future = future;}@Overridepublic void run() {try {
                System.out.println("子线程等待主线程运算完成····");
                Integer integer = future.get();
                System.out.println("子线程完成后续运算:" + integer * integer);} catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();}}}public static void main(String[] args) throws InterruptedException {
        int intermediateResult;
        CompletableFuture<Integer> future = new CompletableFuture<>();// 启动子线程new Thread(new Compute(future)).start();
        System.out.println("启动主线程");
        Thread.sleep(2000);
        System.out.println("主线程计算完成");// 假设主线程计算结果为 100
        intermediateResult = 100;// 传递主线程的计算结果给子线程
        future.complete(intermediateResult);}
}// 输出
启动主线程
    子线程等待主线程运算完成····
    主线程计算完成
    子线程完成后续运算:10000

1.3.2 supplyAsync

CompletableFuture 的 supplyAsync 可以将一个正常的方法以异步的方式来执行:

public class J3_SupplyAsync {private static Integer compute() {try {
            Thread.sleep(2000);} catch (InterruptedException e) {
            e.printStackTrace();}
        System.out.println("子线程计算完成");return 100;}public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(J3_SupplyAsync::compute);
        System.out.println("主线程等待子线程计算完成");
        Integer integer = supplyAsync.get();
        System.out.println("主线程计算完成:" + integer * integer);}
}

1.3.3 流式调用

CompletableFuture 支持大部分流式处理的特性,示例如下:

public class J4_StreamingCall {private static Integer compute() {
        System.out.println("compute所在线程:" + Thread.currentThread().getId());try {
            Thread.sleep(1000);} catch (InterruptedException e) {
            e.printStackTrace();}return 100;}private static Integer multi(Integer integer) {try {
            System.out.println("multi所在线程:" + Thread.currentThread().getId());
            Thread.sleep(1000);} catch (InterruptedException e) {
            e.printStackTrace();}return integer * integer;}private static void accept(Integer integer) {
        System.out.println("accept所在线程:" + Thread.currentThread().getId());
        System.out.println("accept方法消费掉计算结果:" + integer);}public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> future = CompletableFuture.supplyAsync(J4_StreamingCall::compute).thenApply(J4_StreamingCall::multi).thenAccept(J4_StreamingCall::accept)   //值在这一步被消费掉了.thenAccept(-> System.out.println("运算结果:" + x));
        future.get(); //类似于流式计算的惰性求值,如果缺少这一步,不会有任何输出}
}

1.3.4 组合多个 CompletableFuture

除了使用单个的 CompletableFuture,还可以通过 thenCompose 或 thenCombineAsync 来组合多个 CompletableFuture:

public class J6_Combination {private static Integer compute() {
        System.out.println("compute 所在线程:" + Thread.currentThread().getId());return 100;}private static Integer multi(Integer integer) {
        System.out.println("epr 所在线程:" + Thread.currentThread().getId());return integer * integer;}public static void main(String[] args) throws ExecutionException, InterruptedException {// 组合实现方式1 thenCompose 一个计算的输入依赖另外一个计算的结果
        CompletableFuture<Void> future01 = CompletableFuture.supplyAsync(J6_Combination::compute).thenCompose(-> CompletableFuture.supplyAsync(() -> multi(x))).thenAccept(-> System.out.println("运算结果:" + x));    // 运算结果:10000
        future01.get();        System.out.println();// 组合实现方式2 thenCombineAsync 两个计算之间不依赖
        CompletableFuture<Integer> future02 = CompletableFuture.supplyAsync(J6_Combination::compute);
        CompletableFuture<Integer> future03 = CompletableFuture.supplyAsync(() -> J6_Combination.multi(100));
        CompletableFuture<Integer> futureAll = future02.thenCombineAsync(future03, (x, y) -> x + y);
        System.out.println("运算结果:" + futureAll.get()); // 运算结果:10100}
}

2.资源独享线程-ThreadLocal

ThreadLocal 是以增加资源的方式来避免竞态,它会为每一个线程创建一份私有的资源,从而避免对公共资源的竞争。实例如下:

/**
 * 线程不安全的SimpleDateFormat
 */
public class J1_ThreadUnsafe {private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");private static int sum = 1000;private static CountDownLatch countDownLatch = new CountDownLatch(sum);private static AtomicInteger atomicInteger = new AtomicInteger(0);static class Task implements Runnable {@Overridepublic void run() {try {
                Date parse = sdf.parse("2018-08-08 08:08:08");
                System.out.println(parse);
                atomicInteger.incrementAndGet();} catch (ParseException e) {
                e.printStackTrace();} finally {
                countDownLatch.countDown();}}}public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);for (int i = 0; i < sum; i++) {
            executorService.execute(new Task());}
        countDownLatch.await();
        System.out.println("格式化成功次数为:" + atomicInteger.get());}
}

因为 SimpleDateFormat 是线程不安全的,因此其格式化成功的次数总是小于 100 次,此时可以使用 ThreadLocal 进行改写,让每个线程都持有自己独立的格式化器,具体如下:

public class J2_ThreadSafe {private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<>();private static int sum = 1000;private static CountDownLatch countDownLatch = new CountDownLatch(sum);private static AtomicInteger atomicInteger = new AtomicInteger(0);static class Task implements Runnable {@Overridepublic void run() {try {// 如果当前线程中不存在该值,则创建一个if (threadLocal.get() == null) {
                    threadLocal.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));}// 使用线程私有的SimpleDateFormat
                Date parse = threadLocal.get().parse("2018-08-08 08:08:08");
                System.out.println(parse);
                atomicInteger.incrementAndGet();} catch (ParseException e) {
                e.printStackTrace();} finally {
                countDownLatch.countDown();}}}public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);for (int i = 0; i < sum; i++) {
            executorService.execute(new Task());}
        countDownLatch.await();
        System.out.println("格式化成功次数为:" + atomicInteger.get());
        executorService.shutdown();}
}

这篇关于Java 多线程的返回对象和资源独享线程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/350642

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

JDK21对虚拟线程的几种用法实践指南

《JDK21对虚拟线程的几种用法实践指南》虚拟线程是Java中的一种轻量级线程,由JVM管理,特别适合于I/O密集型任务,:本文主要介绍JDK21对虚拟线程的几种用法,文中通过代码介绍的非常详细,... 目录一、参考官方文档二、什么是虚拟线程三、几种用法1、Thread.ofVirtual().start(

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

Java中的.close()举例详解

《Java中的.close()举例详解》.close()方法只适用于通过window.open()打开的弹出窗口,对于浏览器的主窗口,如果没有得到用户允许是不能关闭的,:本文主要介绍Java中的.... 目录当你遇到以下三种情况时,一定要记得使用 .close():用法作用举例如何判断代码中的 input