java8关于CompletableFuture使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package com.xxx.tools.demo.forker;

import lombok.Data;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static com.xxx.tools.demo.forker.CompletableFutureTest.delay;
import static com.xxx.tools.demo.forker.CompletableFutureTest.random;

//import java.util.stream.Stream;

/**
*/
public class CompletableFutureTest {
List<Shop> shops = Arrays.asList(new Shop("BP1"), new Shop("BP2"), new Shop("BP3"), new Shop("BP4"));
public final Executor executor = Executors.newFixedThreadPool(Math.max(shops.size(), 100), r->{
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("shopPool");
return t;
});
public final Executor thenCombinePool = Executors.newFixedThreadPool(Math.max(shops.size(), 100), r->{
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("thenCombine");
return t;
});
public static final Random random = new Random();
public static void delay() {
int delay = 1000;
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public List<CompletableFuture<String>> findPrice(String product){
// public Stream<CompletableFuture<String>> findPrice(String product){
return shops.stream()
.map(shop -> CompletableFuture.supplyAsync(() -> shop.getPrice(product),executor))
// .map(priceStr->priceStr.thenApply())实时转换
.map(priceStr->priceStr.thenApply(str->str+":thenApply"))
// .map(priceStr->priceStr.thenCompose())上一步结果,接着异步(与上一个同步)
.map(priceStr->priceStr.thenCompose((str) -> CompletableFuture.supplyAsync(
()->{
delay();
// System.out.println("thenCompose---name:"+Thread.currentThread().getName());
return str+":thenCompose";
},executor
)))
// .map(priceStr->priceStr.thenCombine())上一步结果,和下一个异步结合
.map(priceStr->priceStr.thenCombine(CompletableFuture.supplyAsync(()->{
delay();
// System.out.println("thenCombine---name:"+Thread.currentThread().getName());
return ":thenCombine";
},thenCombinePool),(a,b)->a+b))
.collect(Collectors.toList());

// return collect.stream()
// .map(CompletableFuture::join)
// .collect(Collectors.toList());

}
@Test
public void test1(){
long start = System.nanoTime();
// List<String> myPhone = findPrice("myPhone").stream()
// .map(CompletableFuture::join)
// .collect(Collectors.toList());
// System.out.println(myPhone);
// long run =(System.nanoTime()-start)/1_000_000;
// System.out.println("1运行了:"+run);

CompletableFuture[] myPhones = (CompletableFuture[]) findPrice("myPhone").stream()
.map(f -> f.thenAccept(System.out::println))
.toArray(size -> new CompletableFuture[size]);
CompletableFuture.allOf(myPhones).join();
long run1 =(System.nanoTime()-start)/1_000_000;
System.out.println("2运行了:"+run1);

}


}
@Data
class Shop {
private String name;
public Shop(String name) {
this.name = name;
}
public String getPrice(String product){
return calculatePrice(product);
}
private String calculatePrice(String product){
delay();
return String.format("%s:%.2f:%s",name,random.nextDouble()*product.charAt(0)+product.charAt(1),Discount.Code.GOLD);
}
}



for (String B00 : b00s) {
bzzsglService.synZsxx(B00);
}

改多线程1

ExecutorService executor = Executors.newFixedThreadPool(5);
try{
List<CompletableFuture<Void>> futures = b00s.stream()
.map(B00 -> CompletableFuture.runAsync(() -> {
bzzsglService.synZsxx(B00);
}, executor))
.collect(Collectors.toList());

CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
}catch (Exception e){
e.printStackTrace();
}finally {
executor.shutdown();
}



改多线程2
ExecutorService personThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
try{
List<Future<?>> batchFutures = new ArrayList<>();
batchFutures.add(personThreadPool.submit(()->{}));
for (Future<?> f : batchFutures) {
try {
f.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
personThreadPool.shutdown();
}