知乎专栏 |
目录
Supplier<String> supplier = () -> "hello, world"; String result = supplier.get(); System.out.println(result); Supplier stringSupplier = () -> new String("Hi Neo"); String string = stringSupplier.get(); System.out.println(string); Supplier<LocalDateTime> currentTime = () -> LocalDateTime.now(); LocalDateTime now = currentTime.get(); // 计算当前时间 Optional<String> optional = Optional.ofNullable("hello"); String orElseGet = optional.orElseGet(() -> "world"); Supplier userSupplier= () -> new User(1,"netkiller"); User user=userSupplier.get(); System.out.println(user.getName());
package cn.netkiller.test; import java.util.function.Supplier; public class TestSupplier { private final int age = 24; TestSupplier() { System.out.println(age); } public static void main(String[] args) { Supplier<TestSupplier> supplier = TestSupplier::new; //调用get()方法,此时会调用对象的构造方法,即获得到真正对象 supplier.get(); System.out.println(supplier.get().test()); TestSupplier test = supplier.get(); System.out.println(test.test()); } private String test() { return "Helloworld!!!"; } }
package cn.netkiller.test; import java.util.function.Supplier; public class TestSupplier { private final int age = 24; private final String name; TestSupplier(String name) { this.name = name; // System.out.println(name); } public static void main(String[] args) { Supplier<String> stringSupplier = () -> { return "test1"; }; System.out.println(stringSupplier.get()); Supplier<String> stringSupplier1 = () -> "test2"; System.out.println(stringSupplier1.get()); Supplier<TestSupplier> testSupplier = () -> new TestSupplier("Neo"); System.out.println(testSupplier.get().name); // String name = "Netkiller"; // Supplier<TestSupplier> testSupplier1 = (name) -> {new TestSupplier(name)}; // System.out.println(testSupplier1.get().name); // System.out.println(test.test()); } private String test() { return "Helloworld!!!"; } }
package cn.netkiller.test; import java.util.concurrent.ExecutionException; import java.util.function.Supplier; public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println(Thread.currentThread()); process(() -> { System.out.println(Thread.currentThread().getName() + " Process..."); return "Test"; }); Supplier<String> stringSupplier1 = () -> "netkiller"; process(stringSupplier1); } public static <T> void process(Supplier<T> supplier) { // System.out.println(Thread.currentThread().getName() + " Process..."); // CompletableFuture<T> runAsync = CompletableFuture.supplyAsync(supplier); // runAsync.join(); // System.out.println(variable.get()); T value = supplier.get(); System.out.println(value); } }