代码:
我找的博客:https://www.cnblogs.com/happyliu/archive/2018/08/12/9462703.html
第二段代码:
这里设置的是守护线程。
代码:
package three.completeFuture;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
public class ComplateableFutureExample3 {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Callable<Integer>> tasks = IntStream.range(0, 10).boxed().map(i -> (Callable<Integer>) () -> get()).collect(toList());
executorService.invokeAll(tasks).stream().map(future -> {
try {
return future.get();
} catch (Exception e) {
throw new RuntimeException();
}
}).parallel().forEach(ComplateableFutureExample3::display);
}
private static void display(int data) {
int value = ThreadLocalRandom.current().nextInt(20);
try {
System.out.println(Thread.currentThread().getName() + " display will be sleep " + data);
TimeUnit.SECONDS.sleep(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " display execute down " + data);
}
private static int get() {
int value = ThreadLocalRandom.current().nextInt(20);
try {
System.out.println(Thread.currentThread().getName() + " get will be sleep " + value);
TimeUnit.SECONDS.sleep(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " get execute down " + value);
return value;
}
}
改进:
package three.completeFuture;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
public class ComplateableFutureExample4 {
public static void main(String[] args) throws InterruptedException {
IntStream.range(0, 10).boxed().forEach(i->CompletableFuture.supplyAsync(ComplateableFutureExample4::get).thenAccept(ComplateableFutureExample4::display).whenComplete((v,t)->System.out.println(i+" DONE")));
Thread.currentThread().join();
}
private static void display(int data) {
int value = ThreadLocalRandom.current().nextInt(20);
try {
System.out.println(Thread.currentThread().getName() + " display will be sleep " + data);
TimeUnit.SECONDS.sleep(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " display execute down " + data);
}
private static int get() {
int value = ThreadLocalRandom.current().nextInt(20);
try {
System.out.println(Thread.currentThread().getName() + " get will be sleep " + value);
TimeUnit.SECONDS.sleep(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " get execute down " + value);
return value;
}
}
内部内置了一个线程池,并且是守护线程,并且是forkJion的线程池。
---56---