例子
public class RUN {
public static void main(String[] args) {
String msgA = "Hello ";
String msgB = "World ";
System.out.println(method(()->msgA+msgB));
}
private static String method(Supplier<String> s){
return s.get();
}
}
System.out.println(method(()->msgA+msgB));的lambda表达式重写了get方法,所以s.get执行的就是msgA+msgB
接口分析
/**
* Represents a supplier of results.
*
* <p>There is no requirement that a new or distinct result be returned each
* time the supplier is invoked.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #get()}.
*
* @param <T> the type of results supplied by this supplier
*
* @since 1.8
*/
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
@FunctionalInterface这种类型的接口也称为SAM接口,即Single Abstract Method interfaces。
那么就可以使用Lambda表达式来表示该接口的一个实现(注:JAVA 8 之前一般是用匿名类实现的):
提醒:加不加@FunctionalInterface对于接口是不是函数式接口没有影响,该注解知识提醒编译器去检查该接口是否仅包含一个抽象方法
CompletableFuture中的Supplier
/**
* Returns a new CompletableFuture that is asynchronously completed
* by a task running in the given executor with the value obtained
* by calling the given Supplier.
*
* @param supplier a function returning the value to be used
* to complete the returned CompletableFuture
* @param executor the executor to use for asynchronous execution
* @param <U> the function's return type
* @return the new CompletableFuture
*/
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}
可以异步的创建一个CompletableFuture线程,并且可以通过supplier传入需要异步执行的代码
代码示例
package com.bilibili.juc.cf;
import java.util.concurrent.*;
/**
* @auther zzyy
* @create 2022-01-16 16:27
*/
public class CompletableFutureBuildDemo
{
public static void main(String[] args) throws ExecutionException, InterruptedException
{
ExecutorService threadPool = Executors.newFixedThreadPool(3);
//无返回值
// CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
// System.out.println(Thread.currentThread().getName());
// //暂停几秒钟线程
// try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
// },threadPool);
//
// System.out.println(completableFuture.get());
//有返回值
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName());
//暂停几秒钟线程
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
return "hello supplyAsync";
},threadPool);
System.out.println(completableFuture.get());
threadPool.shutdown();
}
}
在这里面supplier的get方法被重写为
System.out.println(Thread.currentThread().getName());
//暂停几秒钟线程
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
return "hello supplyAsync";