私はCompleteableFuture
操作を連鎖するための実証例を作成していると私は私が近いんだけど、私は欠けている何かがあると思います。すべてがmain()
の最後の「並行して、ケーキを構築する」条項を除いてコンパイルされます。のJava 8 thenApply()とthenAccept()
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.*;
import java.time.*;
// Use decorator pattern to build up the cake:
interface Cake_ {
String describe();
}
class Cake implements Cake_ {
private int id;
public Cake(int id) { this.id = id; }
@Override
public String describe() {
return "Cake " + id;
}
}
abstract class Decorator implements Cake_ {
protected Cake_ cake;
public Decorator(Cake_ cake) {
this.cake = cake;
}
@Override
public String describe() {
return cake.describe();
}
@Override
public String toString() {
return describe();
}
}
class Frosted extends Decorator {
public Frosted(Cake_ cake) {
super(cake);
}
@Override
public String describe() {
return cake.describe() + " Frosted";
}
}
class Decorated extends Decorator {
public Decorated(Cake_ cake) {
super(cake);
}
@Override
public String describe() {
return cake.describe() + " Decorated";
}
}
// For the cake-building assembly line:
class CreateCakes implements Supplier<Cake> {
private int id;
public CreateCakes(int id) {
this.id = id;
}
@Override
public Cake get() {
return new Cake(id);
}
}
class FrostCakes implements Function<Cake, Frosted> {
@Override
public Frosted apply(Cake cake) {
return new Frosted(cake);
}
}
class DecorateCakes implements Consumer<Frosted> {
public Decorated result;
@Override
public void accept(Frosted fc) {
result = new Decorated(fc);
}
}
public class Test {
public static int NUM_OF_CAKES = 20;
public static void main(String[] args) {
// Change from the default number of threads:
System.setProperty(
"java.util.concurrent.ForkJoinPool" +
".common.parallelism", "" + NUM_OF_CAKES);
// Test/demonstrate the decorator pattern:
List<Cake_> decorated =
IntStream.range(0, NUM_OF_CAKES)
.mapToObj(Cake::new)
.map(Frosted::new)
.map(Decorated::new)
.collect(Collectors.toList());
decorated.forEach(System.out::println);
// Build cakes in parallel:
List<CompletableFuture<?>> futures =
IntStream.range(0, NUM_OF_CAKES)
.mapToObj(id -> new CreateCakes(id))
.map(CompletableFuture::supplyAsync)
.thenApply(new FrostCakes())
.thenAccept(new DecorateCakes())
.collect(Collectors.toList());
futures.forEach(CompletableFuture::join);
}
}
私はfutures
リストの定義の中でいくつかの基本的な理解が欠けている実現が、私は何を表示することを含めましたI 'これを達成しようとする:ケーキ製造プロセスの一部が並行して実行されるケーキ工場。
コンパイルエラーが表示されたら、コンパイルエラーを投稿してください。 –
ストリーム上でthenApple()を呼び出しています。 Streamには、thenApply()メソッドはありません。 –