JUC-Future、CompletionService、CompletableFuture

并发任务执行,取结果归集

1. Future

1.1. 代码示例

public class FutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        StopWatch watch = new StopWatch();
        watch.start();

        //线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10)) ;

        //结果集
        List<String> list = new ArrayList<>();
        List<Future<String>> listFuture = new ArrayList<>();

        for (int i = 0; i < 3; i++){
            int finalI = i;
            listFuture.add(executor.submit(() -> {
                if (finalI == 0){
                    Thread.sleep(5000);
                }else if(finalI == 1){
                    Thread.sleep(3000);
                }else if(finalI ==2){
                    Thread.sleep(1000);
                }
                System.out.println(finalI);
                return finalI+"";
            }));
        }

        //结果归集(结果处理)
        for (int i = 0; i < listFuture.size(); i++){
            Future<String> future = listFuture.get(i);
            while (true){
                if (future.isDone()){
                    String s = future.get();
                    Thread.sleep(500);
                    list.add(s);
                    System.out.println("获取结果:"+s);
                    break;
                }else{
                    //System.out.println("等待");
                    //Thread.sleep(1000);
                }
            }

        }
        System.out.println("list="+list);
        watch.stop();
        System.out.println(watch.prettyPrint());

    }

}

1.2. 运行结果

在这里插入图片描述

1.3. 结果分析

返回的结果是[0, 1, 2],即使后边的任务先执行完,也要等之前加入的任务执行完才能拿到结果。如果对结果的处理也是一个非常费时的操作,那么在等待前面的任务执行完才能处理,这等待的时间就浪费掉了。

2. CompletionService

CompletionService是JDK8才有的,相对于之前版本的Future而言,CompletionService的优势是能后尽可能快的得到执行完成的任务。所以使用CompletionService能够降低总执行时间。

2.1. 代码示例

public class CompletionServiceTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        StopWatch watch = new StopWatch();
        watch.start();

        //线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10)) ;

        CompletionService<String> completionService = new ExecutorCompletionService(executor);

        //结果集
        List<String> list = new ArrayList<>();
        List<Future<String>> listFuture = new ArrayList<>();

        for (int i = 0; i < 3; i++){
            int finalI = i;
            listFuture.add(completionService.submit(() -> {
                if (finalI == 0){
                    Thread.sleep(5000);
                }else if(finalI == 1){
                    Thread.sleep(3000);
                }else if(finalI == 2){
                    Thread.sleep(1000);
                }
                System.out.println(finalI);
                return finalI+"";
            }));
        }


        //结果归集(结果处理)
        for (int i = 0; i < 3; i++){
            String s = completionService.take().get();
            Thread.sleep(500);
            list.add(s);
            System.out.println("获取结果:"+s);
        }

        System.out.println("list="+list);

        watch.stop();
        System.out.println(watch.prettyPrint());
    }

}

2.2. 运行结果

在这里插入图片描述

2.3. 结果分析

返回的结果是[2, 1, 0],可以清楚的看出谁先完成任务就先处理谁的结果。花费时间比Future短。

2.4. 扩展

CompletionService还适用于N选1的场景,例如同时从不同的渠道获取数据,当返回任何一个可用的结果即可。这种场景Future是实现不了的。

2.5. CompletionService接口实现

在这里插入图片描述

3. CompletableFuture——异步编程

3.1. CompletableFuture类图

在这里插入图片描述

3.2. 创建CompletableFuture对象

//使用默认线程池
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)

//使用默认线程池
static CompletableFuture<Void> runAsync(Runnable runnable)

//可以指定线程池
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor)

//可以指定线程池
static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor)                                          

根据不同的业务类型创建不同的线程池,以避免互相干扰

3.3. 实现的Future和CompletionStage接口

实现异步编程:串行关系、并行关系、汇聚关系。

3.3.1. Future接口

用来解决异步操作什么时候结束;以及获取异步操作的结果。

3.3.2. CompletionStage接口

3.3.2.1. 串行关系
CompletionStage<R> thenApply(fn);
CompletionStage<R> thenApplyAsync(fn);
CompletionStage<Void> thenAccept(consumer);
CompletionStage<Void> thenAcceptAsync(consumer);
CompletionStage<Void> thenRun(action);
CompletionStage<Void> thenRunAsync(action);
CompletionStage<R> thenCompose(fn);
CompletionStage<R> thenComposeAsync(fn);
3.3.2.2. 汇聚关系AND
CompletionStage<R> thenCombine(other, fn);
CompletionStage<R> thenCombineAsync(other, fn);
CompletionStage<Void> thenAcceptBoth(other, consumer);
CompletionStage<Void> thenAcceptBothAsync(other, consumer);
CompletionStage<Void> runAfterBoth(other, action);
CompletionStage<Void> runAfterBothAsync(other, action);
3.3.2.3. 汇聚关系OR
CompletionStage applyToEither(other, fn);
CompletionStage applyToEitherAsync(other, fn);
CompletionStage acceptEither(other, consumer);
CompletionStage acceptEitherAsync(other, consumer);
CompletionStage runAfterEither(other, action);
CompletionStage runAfterEitherAsync(other, action);
3.3.2.4. 异常描述
CompletionStage exceptionally(fn);
CompletionStage<R> whenComplete(consumer);
CompletionStage<R> whenCompleteAsync(consumer);
CompletionStage<R> handle(fn);
CompletionStage<R> handleAsync(fn);
### JUC-II中变址寻址的微指令实现细节 #### 1. 变址寻址的基本概念 变址寻址是一种通过基址寄存器与偏移量相加生成有效地址的寻址方式。其核心思想是将指令中的偏移量字段与指定的基址寄存器内容相加,从而计算出目标地址[^1]。在JUC-II模型机中,这种寻址方式常用于数组访问和间接跳转等场景。 #### 2. 微指令的设计原则 微指令是控制计算机硬件执行具体操作的最小单位。在JUC-II模型机中,微指令需要明确描述每一步的操作,包括数据路径的选择、算术逻辑单元(ALU)的操作以及存储器的访问等[^2]。对于变址寻址,微指令设计需满足以下要求: - 提取指令中的偏移量。 - 获取基址寄存器的内容。 - 执行加法操作以生成有效地址。 - 使用有效地址访问内存或寄存器。 #### 3. 微指令的具体实现 以下是针对JUC-II模型机中变址寻址的微指令实现细节: ##### (1) 提取偏移量 从当前指令中提取偏移量字段,并将其存储到临时寄存器中。假设偏移量位于指令的低16位,则微指令可以表示为: ```plaintext MicroOp1: TempReg ← Instruction[15:0] ``` ##### (2) 获取基址寄存器内容 读取指定基址寄存器的内容,并将其加载到另一个临时寄存器中。例如,如果基址寄存器为`Rb`,则微指令为: ```plaintext MicroOp2: BaseRegContent ← Rb ``` ##### (3) 计算有效地址 将偏移量与基址寄存器内容相加,生成有效地址。此操作通常由ALU完成: ```plaintext MicroOp3: EffectiveAddress ← BaseRegContent + TempReg ``` ##### (4) 访问目标地址 使用计算出的有效地址访问内存或寄存器。例如,如果目标是内存单元,则微指令为: ```plaintext MicroOp4: Data ← Memory[EffectiveAddress] ``` #### 4. 微指令的编码形式 微指令的编码形式决定了其在硬件中的实现方式。在JUC-II模型机中,微指令通常采用水平型或垂直型编码[^2]。以下是水平型微指令的一个示例: ```plaintext | 控制信号 | 数据路径选择 | ALU操作 | 存储器访问 | |----------|--------------|---------|------------| | 1 | Src1: BaseRegContent, Src2: TempReg | Add | MemRead | ``` 在此示例中,控制信号指定了ALU执行加法操作,并且选择了`BaseRegContent`和`TempReg`作为输入源。同时,还启用了存储器读操作。 #### 5. 实现中的注意事项 - 确保基址寄存器和偏移量的范围符合硬件限制。 - 如果有效地址超出内存范围,应触发异常处理机制。 - 微指令设计需与硬件结构紧密配合,确保每一步操作都能正确映射到具体的控制信号。 #### 示例代码 以下是一个基于JUC-II模型机的变址寻址微程序伪代码示例: ```plaintext # 提取偏移量 MicroOp1: TempReg ← Instruction[15:0] # 获取基址寄存器内容 MicroOp2: BaseRegContent ← Rb # 计算有效地址 MicroOp3: EffectiveAddress ← BaseRegContent + TempReg # 访问目标地址 MicroOp4: Data ← Memory[EffectiveAddress] ``` #### 6. 相关理论支持 通过设计控制器的微程序,可以实现JUC-II模型机的指令系统,并加深对计算机结构和工作原理的理解。变址寻址作为其中一种重要的寻址方式,其微程序设计对于理解指令执行过程具有重要意义。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值