四大函数式接口
lambda表达式、链式编程、函数式接口、Stream流式计算
函数式接口:只有一个方法的接口:
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
//可以简化编程,在新版框架含有大量应用函数式接口
function
public class Test01 {
public static void main(String[] args) {
/**
* Function,一个传入参数,一个返回值
* 只要是函数式接口,就可以使用lambda表达式
*/
/*Function<String, String> function = new Function<String, String>() {
@Override
public String apply(String s) {
return s;
}
};*/
Function<String, String> function = (s)->{ return s; };
System.out.println(function.apply("set"));
}
}
Predicate
断定型接口;有一个输入参数,返回类型只能是 boolean
public class Test02 {
public static void main(String[] args) {
/*Predicate<String> predicate =new Predicate<String>(){
@Override
public boolean test(String s) {
if ("abc".equals(s)) {
return true;
}
return false;
}
};*/
Predicate<String> predicate=(s)->{if ("abc".equals(s)) {
return true;
}
return false;
};
System.out.println(predicate.test("as"));
System.out.println(predicate.test("abc"));
}
}
Consumer
消费型接口,只有输入,没有输出
public class Teat03 {
public static void main(String[] args) {
/*Consumer<String > consumer = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};*/
Consumer<String > consumer =(str)->{
System.out.println(str);
};
consumer.accept("qwerr");
}
}
supplier
供给型,没有传入参数,只有输出
public class Test04 {
public static void main(String[] args) {
Supplier<String> supplier = new Supplier<String>() {
@Override
public String get() {
return "这是一个供给型接口1";
}
};
Supplier<String> supplier2 = ()->{return "这是一个供给型接口2";};
System.out.println(supplier.get());
System.out.println(supplier2.get());
}
}
Stream流式计算
什么是Stream流式计算
大数据=存储+计算
集合、MySql本质都是用来存储的
计算都交给流去处理
看一道题
package com.fly.juc.function;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
/**
* 现有5个用户!筛选
* 1、ID必须为奇数
* 2、年龄必须小于24岁
* 3、用户名转换为大写字母
* 4、用户名倒着排序
* 5、只输出一个用户
*/
public class StreamTest {
public static void main(String[] args) {
User user1 = new User(1,"as",18);
User user2 = new User(2,"awers",19);
User user3 = new User(3,"aswere",28);
User user4 = new User(4,"axcs",32);
User user5 = new User(5,"asds",21);
User user6 = new User(6,"axdcs",15);
List<User> users = Arrays.asList(user1, user2, user3, user4, user5, user6);
users.stream()
.filter(u->{return u.getId()%2!=0;})
.filter(u->{return u.getAge()<24;})
.map(user ->{return user.getName().toUpperCase();} )
.sorted((u1,u2)->{return u2.compareTo(u1);})
.limit(1)
.forEach(System.out::println);
}
}
class User{
private int id ;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
ForkJoin
什么是ForkJoin
ForkJoin在JDK1.7,并行执行任务,大数据量!
大数据: Map Reduce( 把大任务拆分成小任务)
ForkJoin特点: 工作窃取
使用
package com.czp.forkjoin;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
public class Test {
public static void main(String[] args) {
// test1(1L, 200_0000_0000L);//执行时间为10570毫秒 sum = -2914184820805067776
test2(1L, 200_0000_0000L);//执行时间为202979毫秒 sum = -2935156330807653376
// test3(1L, 200_0000_0000L);//执行时间为15894毫秒 sum = -2914184800805067776
}
public static void test1(long start, long end) {
Instant instant = Instant.now();
long sum = 0;
for (long i = start; i < end; i++) {
sum += i;
}
Instant instant1 = Instant.now();
Duration duration = Duration.between(instant, instant1);
System.out.println("执行时间为" + duration.toMillis() + "毫秒"+"sum = " + sum);
}
public static void test2(long start, long end) {
Instant instant = Instant.now();
ForkJoinPool joinPool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinDemo(start, end);
ForkJoinTask<Long> result = joinPool.submit(task);//提交任务
Long sum = null;
try {
sum = result.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Instant instant1 = Instant.now();
Duration duration = Duration.between(instant, instant1);
System.out.println("执行时间为" + duration.toMillis() + "毫秒"+"sum = " + sum);
}
// stream 并行流
public static void test3(Long start, Long end) {
Instant instant = Instant.now();
//range() 开区间 rangeClosed() 闭区间左开右闭
long sum = LongStream.rangeClosed(start, end).parallel().reduce(0, Long::sum);
Instant instant1 = Instant.now();
Duration duration = Duration.between(instant, instant1);
System.out.println("执行时间为" + duration.toMillis() + "毫秒"+"sum = " + sum);
}
}
/**
* 求和计算的任务
* 1. forkjoinpool 通过它来执行
* 2. 计算任务forkJoinPool, execute(forkjoinTask task)
* 3. 计算类要继承自forkjointask
*/
public class ForkJoinDemo extends RecursiveTask<Long> {
private long start; // 1
private long end; // 20_0000_0000
private long temp = 1_0000L;
public ForkJoinDemo(long start, long end) {
this.start = start;
this.end = end;
}
//计算方法
@Override
protected Long compute() {
if (end - start < temp) {
Long sum = 0L;
for (Long i = start; i < end; i++) {
sum += i;
}
return sum;
} else {
//分支合并计算
long middle = (end + start) / 2; //中间值
ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
task1.fork(); // 拆分任务,把任务压入线程队列
ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
task2.fork();// 拆分任务,把任务压入线程队列
return task1.join() + task2.join();
}
}
}
异步回调
Future设计的初衷: 对将来的某个事件的结果进行建模
/**
* 异步调用: CompletableFuture
* 异步执行
* 成功回调
* 失败回调
*/
public class Demo01 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 发起一个请求
// CompletableFuture future = CompletableFuture.runAsync(()->{
// System.out.println("发送一个没有返回值的异步请求");
// });
//
// System.out.println("1111");
//
// future.get(); //获取执行结果
//callable就可以实现异步调用,为什么要使用CompletableFuture呢,
//CompletableFuture更加强大, callable只有成功回调
//CompletableFuture可以有成功回调,异常(失败)回调
// ExecutorService service = Executors.newCachedThreadPool();
// Future<?> submit = service.submit(() -> {
// System.out.println("这个是callable实现的异步调用,异步是目的,多线程是实现方式!!!");
// });
// System.out.println("1111");
// submit.get(); //获取执行结果
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("供应型接口");
return 200;
});
//返回的结果
Integer integer = completableFuture.whenComplete((t, u) -> {
//成功方法
System.out.println(t); //正常的返回结果
//出现的异常
System.out.println(u); // 错误信息
}).exceptionally((e) -> {
//失败方法
e.printStackTrace();
e.getMessage();
return 500;
}).get();
}
}
上一篇:JUC详解7——线程池