前言
根据各种方式学习总结,留此博客方便个人查阅。
准备
jdk1.8引入了最重要的特性,就是可以在接口中声明static、default接口。
借此,后续众多源码都是在此基础上引用。
接口实例
public interface MyInterface {
//抽象方法
String abstractMethod();
//默认方法
default String defaultMethod() {
return "execute default method";
}
//静态方法
static String staticMethod() {
return "execute static method";
}
}
注意事项
默认方法可以选择实现与否,静态方法不能重新实现
public class MyInterfaceImpl implements MyInterface{
@Override
public String abstractMethod() {
return null;
}
@Override
public String defaultMethod() {
return "execute default method";
}
}
lambda实例
简化传参参数,方法引用。本身没有任何名称,就是一种固定格式,多多练习即可。
lambda使用规范
(参数列表) ‐> {
方法体
}
方式一:
无参数的lambda表达式
() -> new Student();
方式二:
只有一个参数的lambda表达式
x ‐> {
System.out.println(x);
return x;
}
方式三:
多个参数的lambda表达式
(int x,int y) ‐>{
System.out.println(x);
System.out.println(x);
return x+y;
}
方式四:
一个参数和语句的lambda表达式
x ‐> 3+x;
遍历集合
public class LambdaDemo {
public static void main(String[] args) {
String[] language = {"c", "c++", "c#", "java", "python", "go", "hive", "php"};
List<String> languageList = Arrays.asList(language);
//旧的循环方式
for (String s : languageList) {
System.out.println(s + ",");
}
//lambda循环
languageList.forEach((s) -> System.out.println(s + ","));
// jdk1.8前内部类
MyInterface myInterface=new MyInterface() {
@Override
public String abstractMethod() {
return null;
}
};
// jdk1.8后内部类+
MyInterface myInterface1=() -> "xe";
System.out.println(myInterface1.abstractMethod());
}
}
函数式接口
准备
在Java8中为了让现在有的函数能够更加友好的使用Lambda表达式,因此引入了函数式接口这个概念。
众多函数源码使用@FunctionalInterface
/**
* 函数式接口
* 有且只有一个接口
* @ClassName MyFunctionalInterface
* @Description TODO
* @Author lisonglin
* @Date 2021/1/28 21:57
* @Version 1.0
*/
@FunctionalInterface
public interface MyFunctionalInterface {
void execute();
}
public class MyFunctionalDemo {
public static void demo(MyFunctionalInterface myFunctionalInterface){
myFunctionalInterface.execute();
}
public static void main(String[] args){
demo(()-> System.out.println("jdk8"));
}
}
Predicate函数
准备
用于判定满足条件后返回结果
package com.hikktn.jdk8.bean;
/**
* @ClassName Student
* @Description TODO
* @Author lisonglin
* @Date 2021/1/28 22:04
* @Version 1.0
*/
public class Student {
private int id;
private String name;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Student(int id, String name, String sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
public Student() {
}
@Override
public String toString() {
return "Student{" + "id=" + id + ", name='" + name + '\'' + ", sex='" + sex + '\'' + '}';
}
}
package com.hikktn.jdk8.function;
import com.hikktn.jdk8.bean.Student;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/**
* Predicate用于判定满足条件后返回结果
*
* @ClassName MyPredicateDemo
* @Description TODO
* @Author lisonglin
* @Date 2021/1/28 22:03
* @Version 1.0
*/
public class MyPredicateDemo {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(1, "张三", "男"));
students.add(new Student(2, "李四", "女"));
students.add(new Student(3, "王五", "男"));
students.add(new Student(3, "王七", "女"));
// 通过lambda表达式重写方法,各种逻辑判断
List<Student> result = filter(students, (s) -> s.getSex().equals("女"));
System.out.println(result);
List<Student> result2 = filter(students, (s) -> s.getId() >= 3);
System.out.println(result2);
List<Student> students1 = filterAdd(students, (s) -> s.getId() >= 3, (s) -> s.getName().equals("张三"));
System.out.println(students1);
List<Student> student3 = filterOr(students, (s) -> s.getId() == 3, s -> s.getName().equals("李四"));
System.out.println(student3);
List<Student> filterNegate = filterNegate(students, s -> s.getSex().equals("女"));
System.out.println(filterNegate);
List<Student> filterIsEqual = filterIsEqual(students, "张三");
System.out.println(filterIsEqual);
// 并不会报空指针异常
List<Student> filterIsEqual2 = filterIsEqual(students, null);
System.out.println(filterIsEqual2);
}
/**
* test相等于== 满足条件,执行add方法
* boolean test(T t);
*
* @param studentList
* @param predicate
* @return
*/
private static List<Student> filter(List<Student> studentList, Predicate<Student> predicate) {
ArrayList<Student> list = new ArrayList<>();
studentList.forEach(s -> {
if (predicate.test(s)) {
list.add(s);
}
});
return list;
}
/**
* negate相等于!= 不满足条件,执行add方法
* (t) -> !test(t)
*
* @param studentList
* @param predicate
* @return
*/
private static List<Student> filterNegate(List<Student> studentList, Predicate<Student> predicate) {
ArrayList<Student> list = new ArrayList<>();
studentList.forEach(s -> {
if (predicate.negate().test(s)) {
list.add(s);
}
});
return list;
}
/**
* and相等于&& 多条件同时满足,执行add方法
* (t) -> test(t) && other.test(t)
*
* @param studentList
* @param predicate
* @param predicate1
* @return
*/
private static List<Student> filterAdd(List<Student> studentList, Predicate<Student> predicate,
Predicate<Student> predicate1) {
ArrayList<Student> list = new ArrayList<>();
studentList.forEach(s -> {
if (predicate.and(predicate1).test(s)) {
list.add(s);
}
});
return list;
}
/**
* or相等于|| 满足条件,执行add方法
* (t) -> test(t) || other.test(t)
*
* @param studentList
* @param predicate
* @param predicate1
* @return
*/
private static List<Student> filterOr(List<Student> studentList, Predicate<Student> predicate,
Predicate<Student> predicate1) {
ArrayList<Student> list = new ArrayList<>();
studentList.forEach(s -> {
if (predicate.or(predicate1).test(s)) {
list.add(s);
}
});
return list;
}
/**
* isEqual相等于String.equals() 满足条件,执行add方法
*
* @param studentList
* @param studentName
* @return
*/
private static List<Student> filterIsEqual(List<Student> studentList, String studentName) {
ArrayList<Student> list = new ArrayList<>();
studentList.forEach(s -> {
if (Predicate.isEqual(studentName).test(s.getName())) {
list.add(s);
}
});
return list;
}
/**
* jdk11 not和negate一样 != 多了非空判断
*
* @param studentList
* @param predicate
* @return
*/
// private static List<Student> filterNot(List<Student> studentList,
// Predicate<Student> predicate) {
// ArrayList<Student> list = new ArrayList<>();
// studentList.forEach(s -> {
// if (Predicate.not(predicate).test(s)) {
// list.add(s);
// }
// });
// return list;
// }
}
Consume函数
package com.hikktn.jdk8.function;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import com.hikktn.jdk8.bean.Student;
public class MyConsumerDemo {
public static void main(String[] args) {
// 操作list集合
List<String> arrays = new ArrayList<>();
arrays.add("java");
arrays.add("python");
// 遍历list
foreach(arrays, (s) -> System.out.println(s + ","));
// 没有返回值
// 消费者
foreach(arrays, s -> {
if ("java".equals(s)) {
System.out.println(s);
}
});
List<Student> students = new ArrayList<>();
students.add(new Student(1, "张三", "男"));
students.add(new Student(2, "李四", "女"));
students.add(new Student(3, "王五", "男"));
students.add(new Student(3, "王七", "女"));
foreachList(students, s -> System.out.println(s));
System.out.println("===========");
foreachAndThen(students, (s) -> {
if ("2".equals(String.valueOf(s.getId()))) {
System.out.println(s);
}
}, s -> {
if ("王七".equals(s.getName())) {
System.out.println(s);
// 不可直接在acccpt方法里直接操作元素或对象
// java.util.ConcurrentModificationException
// students.add(s);
}
});
// 可以通过内部类add集合后,在使用串行accept
Consumer<Student> consumer= x -> {
if("男".equals(x.getSex())) {
students.add(x);
}
};
Student student=new Student(5,"武士","男");
consumer.accept(student);
System.out.println(students);
}
/**
* accept对对象进行操作,可以使用此方法 void accept(T t);
*
* @param arrays
* @param consumer
*/
public static void foreach(List<String> arrays, Consumer<String> consumer) {
arrays.forEach(s -> consumer.accept(s));
}
/**
* 实例操作对象
*
* @param arrays
* @param consumer
*/
public static void foreachList(List<Student> arrays, Consumer<Student> consumer) {
arrays.forEach(s -> consumer.accept(s));
}
/**
* andThen串行多个条件
*
* @param arrays
* @param consumer
* @param consumer1
*/
public static void foreachAndThen(List<Student> arrays, Consumer<Student> consumer, Consumer<Student> consumer1) {
arrays.forEach(s -> consumer.andThen(consumer1).accept(s));
}
}
Function函数
package com.hikktn.jdk8.function;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import com.hikktn.jdk8.bean.Student;
public class MyFunctionDemo {
public static void main(String[] args) {
String value = "2021";
Integer result = convert(value, (s) -> Integer.parseInt(s) + 222);
System.out.println(result);
// 复杂计算,镶嵌串行使用
// Function <T>:input参数 <R>:output参数
Function<Integer, Integer> function1 =x ->x+1;
Function<Integer, Integer> function2 =x ->x+1;
// compose 源码执行
Integer result2 = function1.apply(function2.apply(2021));
System.out.println(result2);
// (V v) -> apply(before.apply(v))
Function<Integer, Integer> result3 = function1.compose(function2);
System.out.println(result3.apply(2021));
// 多条件,拼接更多的计算
// (T t) -> after.apply(apply(t))
System.out.println(result3.andThen(function1).apply(1000));
// 返回默认参数
System.out.println(Function.identity().apply(10));
// 添加武士
List<Student> students = new ArrayList<>();
students.add(new Student(1, "张三", "男"));
students.add(new Student(2, "李四", "女"));
Student student=new Student(5,"武士","男");
convertStudent(student, s->{
if("武士".equals(s.getName())) {
students.add(s);
}
return students;
});
System.out.println(students);
}
/**
* apply 调用内部类中的实现代码
* @param value
* @param function
* @return
*/
public static Integer convert(String value, Function<String, Integer> function) {
return function.apply(value);
}
/**
* 实例学生对象
* @param student
* @param function
* @return
*/
public static List<Student> convertStudent(Student student, Function<Student,
List<Student>> function) {
return function.apply(student);
}
}
Supplie函数
package com.hikktn.jdk8.function;
import java.util.function.Supplier;
/**
* 用于进行值操作
* @author 12134
*
*/
public class MySupplierDemo {
public static Integer getMin(Supplier<Integer> supplier) {
return supplier.get();
}
public static void main(String[] args) {
// 创建数组
int[] arr = { 100, 20, 50, 30, 99, 101, -50 };
Integer result = getMin(() -> {
int min = arr[0];
for (int i : arr) {
if (i < min) {
min = i;
}
}
return min;
});
System.out.println(result);
}
}
Stream流
package com.hikktn.jdk8.function;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.hikktn.jdk8.bean.Student;
public class MyStreamDemo {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(1, "张三", "男"));
students.add(new Student(2, "李四", "女"));
students.add(new Student(3, "王五", "男"));
students.add(new Student(3, "王七", "女"));
students.add(new Student(3, "王七", "女"));
List<String> result = students.stream() // 流
.filter(s -> s.getId() >= 3) // 筛选
.sorted(Comparator.comparing(Student::getId)) // 排序
.map(Student::getName) // 获取(映射)
.distinct() // 去重
.collect(Collectors.toList());// 转换
System.out.println(result);
// 获取list集合中第二个到第三个学生的信息
List<Student> collect = students.stream() // 流
.limit(3) // 截取
.skip(1) // 跳过 (0代表不跳过)
.collect(Collectors.toList());
System.out.println(collect);
// 获取每个学生的名字长度
List<Integer> collect2 = students.stream().map(Student::getName).map(String::length)
.collect(Collectors.toList());
System.out.println(collect2);
// 短路求值,满足条件立即结束流,返回true(单个匹配,结束循环)
if (students.stream().anyMatch(s -> s.getId() >= 3)) {
System.out.println("ok");
} else {
System.out.println("no");
}
// 全部匹配,有且只有一个不满足条件,返回false
if (students.stream().allMatch(s -> s.getId() >= 3)) {
System.out.println("ok");
} else {
System.out.println("no");
}
// 串行流
Optional<Student> optional = students.stream().filter(s -> s.getId() >= 3) // 筛选
.findAny(); // 多次操作下获取第一个结果
// 判断返回对象是否为空
if (optional.isPresent()) {
System.out.println(optional.get());
}
System.out.println("============");
// 随机获取 (并行流)
for (int i = 0; i < 100; i++) {
Optional<Student> optional2 = students.parallelStream().filter(s -> s.getId() < 3).findAny();
if (optional2.isPresent()) {
System.out.println(optional2.get());
}
}
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(7);
// 求和(归约)
Integer reduce = numbers.stream().reduce(0, (a, b) -> a + b);
System.out.println(reduce);
// 更加简洁的代码
Integer reduce2 = numbers.stream().reduce(0, Integer::sum);
System.out.println(reduce2);
// 可以返回Optional的方式
Optional<Integer> optional3 = numbers.stream().reduce(Integer::sum);
if (optional3.isPresent()) {
System.out.println(optional3.get());
} else {
System.out.println("数据有误");
}
// 获取最大值
Optional<Integer> optional4 = numbers.stream().reduce(Integer::max);
if (optional.isPresent()) {
Integer integer = optional4.get();
System.out.println(integer);
}
// 更加简洁的代码 max
Optional<Integer> optional5 = numbers.stream().max(Integer::compareTo);
if (optional.isPresent()) {
Integer integer = optional5.get();
System.out.println(integer);
}
// 最小值
Optional<Integer> min = numbers.stream().min(Integer::compareTo);
if (min.isPresent()) {
System.out.println(min.get());
}
System.out.println("============");
// 创建流
// of可以接收任意参数,创建不同类型的流
Stream<String> stringStream = Stream.of("1", "2", "3");
stringStream.forEach(d -> System.out.println(d));
System.out.println("============");
Stream<Object> stream = Stream.of("1", "2", 3, true, new St());
stream.forEach(d -> System.out.println(d));
// 创建数组流
Integer[] numbers6 = new Integer[] { 1, 2, 3, 4, 5, 6 };
Stream<Integer> integerStream = Arrays.stream(numbers6);
integerStream.forEach(d -> System.out.println(d));
// 创建文件流
try {
// 获取指定目录下的所有子文件路径
Files.list(Paths.get("C:\\Users\\12134\\Desktop\\个人进阶之旅\\mybat\\1"))
.forEach(path -> System.out.println(path));
} catch (IOException e) {
e.printStackTrace();
}
try {
Files.list(Paths.get("C:\\Users\\12134\\Desktop\\个人进阶之旅\\mybat\\1\\2")).forEach(path -> {
try {
System.out.println(path);
// 读取每一个文件中的内容 必须是文件,不能是文件夹
Files.lines(path).forEach(content -> System.out.println(content));
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
// 生成map集合,key:学生名字,value:学生对象
Map<String, List<Student>> collect3 = students.stream().collect(Collectors.groupingBy(Student::getName));
System.out.println(collect3);
// 统计集合总数
Long collect4 = students.stream().collect(Collectors.counting());
System.out.println(collect4.intValue());
// 简洁方式 counting
long count = students.stream().count();
System.out.println(count);
// 获取序号最大的学生
Optional<Student> optional7 = students.stream().collect(Collectors.maxBy(Comparator.comparing(Student::getId)));
if (optional7.isPresent()) {
Student student = optional7.get();
System.out.println(student);
}
// 简洁方式 max/min
Optional<Student> studentOptional = students.stream().max(Comparator.comparing(Student::getId));
if (studentOptional.isPresent()) {
Student student = studentOptional.get();
System.out.println(student);
}
// 数据汇总
Integer collect5 = students.stream().collect(Collectors.summingInt(Student::getId));
System.out.println(collect5);
// 简洁方式summingInt
int sum = students.stream().mapToInt(Student::getId).sum();
System.out.println(sum);
// 平均值 5个学生学号平均值
Double collect6 = students.stream().collect(Collectors.averagingInt(Student::getId));
System.out.println(collect6);
// 另一种方式
OptionalDouble average = students.stream().mapToDouble(Student::getId).average();
if (average.isPresent()) {
double asDouble = average.getAsDouble();
System.out.println(asDouble);
}
// 返回IntSummaryStatistics{count=5, sum=12, min=1, average=2.400000, max=3}
// 可以进行上面一样的功能,复杂结果返回
IntSummaryStatistics collect7 = students.stream().collect(Collectors.summarizingInt(Student::getId));
System.out.println(collect7);
// 拼接
String collect8 = students.stream().map(Student::getName).collect(Collectors.joining(","));
System.out.println(collect8);
// 分组
Map<String, List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getSex));
System.out.println(map);
// 多级分组
Map<Integer, Map<String, List<Student>>> collect9 = students.stream()
.collect(Collectors.groupingBy(Student::getId, Collectors.groupingBy(Student::getName)));
System.out.println(collect9);
Map<Integer, Long> collect10 = students.stream().collect(Collectors.groupingBy(Student::getId,
Collectors.counting()));
System.out.println(collect10);
}
static class St {
}
}
同步编程
package com.hikktn.jdk8.function;
import java.util.Random;
/**
* 同步编程
* @author 12134
*
*/
public class SyncDemo {
static Random random = new Random();
// 接收文章名称,获取并计算文章分数
public static int getArticleScore(String aname) {
// 等待3秒
int a = calculateArticleScore(aname);
// 等待3秒
int b = calculateArticleScore(aname);
// 等待3秒
int c = calculateArticleScore(aname);
doSomeThingElse();
return a + b + c;
}
// 计算文章分数
public static int calculateArticleScore(String aname) {
// 模拟延迟
otherService();
return random.nextInt(100);
}
// 模拟服务调用延迟
public static void otherService() {
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static void doSomeThingElse() {
System.out.println("exec other things");
}
public static void main(String[] args) {
System.out.println(getArticleScore("demo"));
}
}
异步编程Future
package com.hikktn.jdk8.function;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* 异步编程
* @author 12134
*
*/
public class FutureAsyncDemo {
static Random random = new Random();
// 线程池
static ExecutorService executor = Executors.newCachedThreadPool();
// 接收文章名称,获取并计算文章分数
public static int getArticleScore(String aname) {
// Future 会等待所有进程一起结束,而不是Future线程,则不需要等待
// 非阻塞
Future<Integer> futureA = calculate();
Future<Integer> futureB = calculate();
Future<Integer> futureC = calculate();
doSomeThingElse();
Integer a = null;
try {
// get():返回Future对象,获取执行结果,如果任务没有完成会阻塞到任务完成再返回。
a = futureA.get();
} catch (InterruptedException e) {
// cancel():取消任务, 取消成功返回true;入参mayInterruptIfRunning表示是否允许取消正在执行中的任务。
futureA.cancel(true);
e.printStackTrace();
} catch (ExecutionException e) {
futureA.cancel(true);
e.printStackTrace();
}
Integer b = null;
try {
b = futureB.get();
} catch (InterruptedException e) {
futureB.cancel(true);
e.printStackTrace();
} catch (ExecutionException e) {
futureB.cancel(true);
e.printStackTrace();
}
Integer c = null;
try {
c = futureC.get();
} catch (InterruptedException e) {
futureC.cancel(true);
e.printStackTrace();
} catch (ExecutionException e) {
futureC.cancel(true);
e.printStackTrace();
}
// 关闭线程池
executor.shutdown();
return a + b + c;
}
public static Future<Integer> calculate() {
return executor.submit(() -> {
// 业务代码
Random random = new Random();
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName());
return random.nextInt(100);
});
}
private static void doSomeThingElse() {
System.out.println("exec other things");
}
public static void main(String[] args) {
System.out.println(getArticleScore("demo"));
}
}
异步编程CompletableFuture
package com.hikktn.jdk8.function;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
public class MyCompletableFutureDemo {
public static void main(String[] args) {
// NotExecutorRunAsync();
// ExecutorRunAsync();
// supplyAsync();
// supplyAsyncError();
// thenApply();
// handleError();
// thenRun();
// thenCombineAsync();
// thenAcceptBoth();
// ApplyToEither();
// RunAfterEither();
// AllOf();
AnyOf();
}
public static void NotExecutorRunAsync() {
// 未设置Executor
// 子线程还没有打印,主线程就结束
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("child run");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("main end");
}
public static void ExecutorRunAsync() {
// 设置自定义线程池
ExecutorService executor = Executors.newFixedThreadPool(100);
// 主线程结束了,也不会关闭子线程
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("child run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, executor);
System.out.println("main end");
executor.shutdown();
}
public static void supplyAsync() {
// supplyAsync有返回值
ExecutorService executor = Executors.newFixedThreadPool(100);
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
try {
System.out.println("异步任务线程:" + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(3);
System.out.println("child run");
} catch (InterruptedException e) {
e.printStackTrace();
}
return 123;
}, executor);
System.out.println("main end");
try {
// 获取结果值
Integer integer = future.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
try {
// 特定处理任务使用的线程
future.whenComplete(new BiConsumer<Integer, Throwable>() {
@Override
public void accept(Integer integer, Throwable throwable) {
System.out.println("结果触发任务线程:" + Thread.currentThread().getName());
System.out.println("特定任务执行");
}
});
} catch (Exception e) {
e.printStackTrace();
}
executor.shutdown();
}
public static void supplyAsyncError() {
ExecutorService executor = Executors.newFixedThreadPool(100);
System.out.println(Thread.currentThread().getName());
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
try {
System.out.println("异步任务线程:" + Thread.currentThread().getName());
int i = 1 / 0;
TimeUnit.SECONDS.sleep(3);
System.out.println("child run");
} catch (InterruptedException e) {
e.printStackTrace();
}
return 123;
}, executor);
System.out.println("main end");
try {
// 特定处理任务使用的线程
future.whenComplete(new BiConsumer<Integer, Throwable>() {
@Override
public void accept(Integer integer, Throwable throwable) {
System.out.println("结果触发任务线程:" + Thread.currentThread().getName());
System.out.println("特定任务执行");
}
});
} catch (Exception e) {
e.printStackTrace();
}
// 异步任务
future.exceptionally(new Function<Throwable, Integer>() {
@Override
public Integer apply(Throwable throwable) {
System.out.println("异常结果触发任务线程:" + Thread.currentThread().getName());
System.out.println("异步任务执行失败:" + throwable.getMessage());
return null;
}
});
}
private static void thenApply() {
ExecutorService executor = Executors.newFixedThreadPool(100);
//
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
int value = new Random().nextInt(100);
System.out.println(value);
return value;
// thenApply 串联两个任务
}, executor).thenApply(value -> {
int result = value * 10;
System.out.println(result);
return result;
});
try {
Integer result = future.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
future.cancel(true);
} catch (ExecutionException e) {
e.printStackTrace();
future.cancel(true);
} finally {
executor.shutdown();
}
}
private static void handleError() {
ExecutorService executor = Executors.newFixedThreadPool(100);
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
int value = new Random().nextInt(100);
int i = 1 / 0;
System.out.println(value);
return value;
// handle 当第一个任务出现异常后,第二个任务会对该异常进行后续的处理,完成串性操作。
}, executor).handle(new BiFunction<Integer, Throwable, Integer>() {
@Override
public Integer apply(Integer integer, Throwable throwable) {
int result = 1;
if (throwable == null) {
result = integer * 10;
System.out.println(result);
} else {
System.out.println(throwable.getMessage());
}
return result;
}
});
try {
Integer result = future.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
future.cancel(true);
} catch (ExecutionException e) {
e.printStackTrace();
future.cancel(true);
} finally {
executor.shutdown();
}
}
private static void thenRun() {
ExecutorService executorService = Executors.newFixedThreadPool(100);
// thenRun 不会返回结果,不会关心是否有结果,也会触发执行
CompletableFuture.supplyAsync(() -> {
int i = new Random().nextInt(100);
return i;
}).thenRun(() -> System.out.println("run方法执行"));
executorService.shutdown();
}
private static void thenCombineAsync() {
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("future1:" + Thread.currentThread().getName());
return "hello";
}, executorService);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("future2:" + Thread.currentThread().getName());
return "itheima";
}, executorService);
// thenCombineAsync 合并任务 也会重新创建线程 两个任务全部完成触发
CompletableFuture<String> result = future1.thenCombineAsync(future2, (f1, f2) -> {
System.out.println("result:" + Thread.currentThread().getName());
return f1 + " " + f2;
}, executorService);
try {
System.out.println(result.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executorService.shutdown();
}
private static void thenAcceptBoth() {
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
int f1 = new Random().nextInt(100);
System.out.println("f1 value:" + f1);
return f1;
}, executorService);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
int f2 = new Random().nextInt(100);
System.out.println("f2 value:" + f2);
return f2;
}, executorService);
// thenAcceptBoth 两个任务全部完成触发
// 当两个任务执行完毕,触发特定任务处理,但不要两个异步任务结果,且不会进行值返回。
future1.thenAcceptBoth(future2, (f1, f2) -> System.out.println(f1 + f2));
executorService.shutdown();
}
private static void runAfterBothAsync() {
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
int f1 = new Random().nextInt(100);
System.out.println("f1 value:" + f1);
return f1;
}, executorService);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
try {
// 不会等待10秒钟
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
int f2 = new Random().nextInt(100);
System.out.println("f2 value:" + f2);
return f2;
}, executorService);
future1.runAfterBothAsync(future2, () -> {
System.out.println("两个任务都已执行完");
executorService.shutdown();
}, executorService);
}
private static void ApplyToEither() {
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future1:" + Thread.currentThread().getName());
return "hello";
}, executorService);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future2:" + Thread.currentThread().getName());
return "itheima";
}, executorService);
// applyToEitherAsync 两个任务任意一个完成触发
// 当两个任务异步任务执行,谁先执行完,就以谁的结果为准,完成后续的业务处理,并且会进行结果值返回。
CompletableFuture<String> result = future1.applyToEitherAsync(future2, (value) -> {
System.out.println("result:" + Thread.currentThread().getName());
return value;
}, executorService);
try {
System.out.println(result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
executorService.shutdown();
}
private static void AcceptEither() {
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future1:" + Thread.currentThread().getName());
return "hello";
}, executorService);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future2:" + Thread.currentThread().getName());
return "itheima";
}, executorService);
// acceptEitherAsync 没有返回值
future1.acceptEitherAsync(future2, (value) -> {
System.out.println("result:" + Thread.currentThread().getName());
System.out.println(value);
executorService.shutdown();
}, executorService);
}
private static void RunAfterEither() {
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future1:" + Thread.currentThread().getName());
return "hello";
}, executorService);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future2:" + Thread.currentThread().getName());
return "itheima";
}, executorService);
// runAfterEitherAsync当两个任务执行,只要有一个任务执行完,则触发特定处理执行,无需使用异步任务的执行结果,且特定处理不会进行值的返回。
future1.runAfterEitherAsync(future2, () -> System.out.println("其中一个任务处理完成了"), executorService);
// 不能先关闭线程池
// executorService.shutdown();
}
private static void AllOf() {
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
int f1 = new Random().nextInt(100);
System.out.println("f1 value:" + 9);
return 9;
}, executorService);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
int f2 = new Random().nextInt(100);
System.out.println("f2 value:" + 64);
return 64;
}, executorService);
CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
int f3 = new Random().nextInt(100);
System.out.println("f3 value:" + 97);
return 97;
}, executorService);
CompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
int f3 = new Random().nextInt(100);
System.out.println("f4 value:" + 11);
return 11;
}, executorService);
CompletableFuture<Integer> future5 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
int f3 = new Random().nextInt(100);
System.out.println("f5 value:" + 65);
return 65;
}, executorService);
// 将线程放进list集合中
List<CompletableFuture<Integer>> list = new ArrayList<>();
list.add(future1);
list.add(future2);
list.add(future3);
list.add(future4);
list.add(future5);
// 多任务组合
// 多个异步任务执行后,才能执行特定业务处理
CompletableFuture<Void> all = CompletableFuture.allOf(list.toArray(new CompletableFuture[] {}));
all.thenRunAsync(() -> {
// 初始化
AtomicReference<Integer> result = new AtomicReference<>(0);
// 异步流
// forEach不能保证线程安全,forEachOrdered可以保证线程安全
list.parallelStream().forEachOrdered(future -> {
try {
Integer value = future.get();
// 修改获取的值 线程不安全
result.updateAndGet(v -> v + value);
System.out.println("修改后的:" + result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
});
}
private static void AnyOf() {
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
int f1 = new Random().nextInt(100);
System.out.println("f1 value:" + f1);
return f1;
}, executorService);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
int f2 = new Random().nextInt(100);
System.out.println("f2 value:" + f2);
return f2;
}, executorService);
CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
int f3 = new Random().nextInt(100);
System.out.println("f3 value:" + f3);
return f3;
}, executorService);
// 将线程放进list集合中
List<CompletableFuture<Integer>> list = new ArrayList<>();
list.add(future1);
list.add(future2);
list.add(future3);
// 多任务组合
// 当多个异步计算,只要有一个结束了,则触发回调处理。
CompletableFuture<Object> all = CompletableFuture.anyOf(list.toArray(new CompletableFuture[] {}));
all.thenRunAsync(() -> {
try {
System.out.println("有一个任务执行完了,其值为:" + all.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
executorService.shutdown();
}
}
Optional
package com.hikktn.jdk8.function;
import java.util.Optional;
import com.hikktn.jdk8.bean.Company;
import com.hikktn.jdk8.bean.Job;
import com.hikktn.jdk8.bean.Student;
public class MyOptional {
public static void main(String[] args) {
Student student = new Student(1, "zhangsan", "男",
Optional.ofNullable(new Job(Optional.ofNullable(new Company("马戏团")))));
Student student2 = new Student(1, "zhangsan", "男",
Optional.ofNullable(new Job(Optional.ofNullable(new Company()))));
getStudentName(student);
// Student student1 = null;
// getStudentInfo(student1);
getStudentInfo2(student);
getCompanyName(student2);
}
public static void getStudentName(Student student) {
// 不含有空对象的Optional
Optional<Student> studentOptional = Optional.ofNullable(student);
if (studentOptional.isPresent()) {
// 存在
System.out.println("student存在:" + studentOptional.get());
// 获取
Optional<String> nameOptional = studentOptional.map(Student::getName);
System.out.println(nameOptional.get());
// 获取下一级对象
Optional<String> optional = studentOptional.flatMap(Student::getJob).flatMap(Job::getCompany)
.map(Company::getName);
System.out.println(optional.get());
} else {
System.out.println("student不存在");
}
}
public static void getStudentInfo(Student student) {
Optional<Student> studentOptional = Optional.ofNullable(student);
try {
// 自定义异常
Student student1 = studentOptional.orElseThrow(MyException::new);
} catch (MyException e) {
e.printStackTrace();
}
}
public static void getStudentInfo2(Student student) {
Optional<Student> student2 = Optional.of(student);
System.out.println(student2);
// Optional<Object> optional = Optional.empty();
Optional<Student> filter = student2.filter(s -> "zhangsan".equals(s.getName()));
System.out.println(filter);
}
public static void getCompanyName(Student student) {
Optional<Student> studentOptional = Optional.ofNullable(student);
if (studentOptional.isPresent()) {
// 如果值没有,返回默认值
String value1 = studentOptional.flatMap(Student::getJob).flatMap(Job::getCompany).map(Company::getName)
.orElse(get("a"));
// 如果值没有,返回默认值(区别:延迟加载)有值时,会直接调用orElse方法,只有Optional里没有值,才会执行orElseGet方法
String value2 = studentOptional.flatMap(Student::getJob).flatMap(Job::getCompany).map(Company::getName)
.orElseGet(() -> get("b"));
System.out.println("a: " + value1);
System.out.println("b: " + value2);
}
}
public static String get(String name) {
System.out.println(name + "执行了方法");
return "exec";
}
}