我已经编写了一个小程序来测试CompletableFuture行为,但不清楚如何在执行任务时创建和使用线程。
package com.my.testprog.concurrjava;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompFuture {
ExecutorService firstExecService = Executors.newFixedThreadPool(2);
ExecutorService secondExecService = Executors.newFixedThreadPool(2);
public CompFuture() {
}
public String returnSalutation(String param) {
System.out.println("RS: " + Thread.currentThread());
return param + " Hello my";
}
public void returnGreetings(String salutation) {
System.out.println("RG: " + Thread.currentThread());
System.out.println("RG: " + salutation + " Friend!");
}
public void testMe(String start) {
System.out.println("TM: " + Thread.currentThread());
CompletableFuture.supplyAsync(() -> returnSalutation(start), firstExecService)
.thenAccept(s -> returnGreetings(s));
}
public static void main(String[] args) {
CompFuture compFuture = new CompFuture();
compFuture.testMe("Java");
compFuture.firstExecService.shutdown();
compFuture.secondExecService.shutdown();
}
}
当我运行程序时,它会显示以下输出:
TM: Thread[main,5,main]
RS: Thread[pool-1-thread-1,5,main]
RG: Thread[main,5,main]
RG: Java Hello my Friend!
我的理解是,它将使用相同的线程来调用“ supplyAsync”和“ thenAccept”方法。但是,以上结果表明仅在单独的线程中执行了“ supplyAsync”,而在主线程中运行了“ thenAccept”。
有人可以详细说明吗?