我想使用异步模式启动CompletableFuture
Java 8-9的线程,这些是我的类和我的线程:
我有3个帖子。我的类包含一个方法myMethod()
Class_1 class_1 = new Class_1();
Class_2 class_2 = new Class_2();
Class_3 class_3 = new Class_3();
如下设置我的Runnable
:
Runnable runnableClass_1 = new Runnable(){
public void run(){
class_1.myMethod();
try { Thread.sleep(0); } catch (InterruptedException e) { e.printStackTrace(); }
}
};
Runnable runnableClass_2 = new Runnable(){
public void run(){
class_2.myMethod();
try { Thread.sleep(0); } catch (InterruptedException e) { e.printStackTrace(); }
}
};
Runnable runnableClass_3 = new Runnable(){
public void run(){
class_3.myMethod();
try { Thread.sleep(0); } catch (InterruptedException e) { e.printStackTrace(); }
}
};
创建线程:
Thread t_1 = new Thread( runnableClass_1 );
Thread t_2 = new Thread( runnableClass_2 );
Thread t_3 = new Thread( runnableClass_3 );
最后,我的问题是如何使用CompletableFuture
异步模式启动这三个线程。
答案 0 :(得分:1)
以下是如何实现相同的内容:
List<String> results = new ArrayList<String>();
CompletableFuture<Void> run1 = CompletableFuture.runAsync(() -> {
pauseSeconds(2);
results.add("first task");
}, service);
CompletableFuture<Void> run2 = CompletableFuture.runAsync(() -> {
pauseSeconds(3);
results.add("second task");
}, service);
CompletableFuture<Void> finisher = run1.runAfterBothAsync(run2,
() -> results.add(results.get(0)+ "&"+results.get(1)),service);
pauseSeconds(4);
System.out.println("finisher.isDone() = "+finisher.isDone());
System.out.println("results.get(2) = "+results.get(2));
// assert(finisher.isDone(), is(true));
// assertThat(results.get(2),is("first task&second task"));
}
public static void pauseSeconds(int num){
try {
Thread.sleep(num);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 1 :(得分:1)
您如何设置(并可能组合)您的期货取决于您的用例:这些期货是否相互依赖?您需要按顺序执行它们还是可以并行运行它们?您是否关心所有三个结果,或者您只是需要先完成哪个未来?
根据您的回答,您可以使用flatMap/bind
组合器(它们具有CompletableFuture
的不同名称,但您可以解决这个问题)按顺序链接您的未来,或者您可以从您的所有期货中产生所有未来当前线程(让它们并行运行),然后等待所有线程完成。您还可以为CompletableFuture
工厂方法指定一个特定的线程池,只使用默认值(ForkJoinPool)。
所有这一切都可以使用vavr提供的Future
的monadic版本非常简洁地完成。但如果您查看documentation,也可以使用CompletableFuture
找出解决方案。
更新/请求示例:
以下示例基本上取自Java 8 in Action github repository,其中提供的期货并行运行,并且所有期货的结果都累积到集合中。您所做的就是将List<Future<T>>
转换为Future<List<T>>
。
final long startTime = System.currentTimeMillis();
final CompletableFuture<String> foo = CompletableFuture.supplyAsync(() -> {
final long timeout = 500;
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("foo on %s sleeping for %s", Thread.currentThread(), timeout));
return "foo";
});
final CompletableFuture<String> bar = CompletableFuture.supplyAsync(() -> {
final long timeout = 100;
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("bar on %s sleeping for %s", Thread.currentThread(), timeout));
return "bar";
});
final CompletableFuture<String> baz = CompletableFuture.supplyAsync(() -> {
final long timeout = 1000;
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("baz on %s sleeping for %s", Thread.currentThread(), timeout));
return "baz";
});
CompletableFuture
.supplyAsync(() -> Stream.of(foo, bar, baz).map(future -> future.join()).collect(Collectors.toList()))
.thenAccept(done -> System.out.println(String.format("Done with all futures %s", done)))
.thenRun(() -> System.out.println(String.format("Running all futures in parallel took %s millis", System.currentTimeMillis() - startTime)));
输出应该是这样的:
bar on Thread[ForkJoinPool.commonPool-worker-2,5,main] sleeping for 100
foo on Thread[ForkJoinPool.commonPool-worker-9,5,main] sleeping for 500
baz on Thread[ForkJoinPool.commonPool-worker-11,5,main] sleeping for 1000
Done with all futures [foo, bar, baz]
Running all futures in parallel took 1007 millis