原创转载请注明出处:http://agilestyle.iteye.com/blog/2427053
completableFuture.get()
package org.fool.java8.completable; import java.util.Optional; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureTest0 { private final static Random RANDOM = new Random(System.currentTimeMillis()); public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<Double> completableFuture = new CompletableFuture<>(); new Thread(() -> { double result = get(); completableFuture.complete(result); }).start(); System.out.println("=========main start no block=========="); Optional.ofNullable(completableFuture.get()).ifPresent(System.out::println); System.out.println("=========main end no block=========="); } private static double get() { try { Thread.sleep(RANDOM.nextInt(10000)); } catch (InterruptedException e) { e.printStackTrace(); } return RANDOM.nextDouble(); } }
Console Output
Note: completableFuture.get() 是阻塞的
CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action)
package org.fool.java8.completable; import java.util.Optional; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureTest1 { private final static Random RANDOM = new Random(System.currentTimeMillis()); public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<Double> completableFuture = new CompletableFuture<>(); new Thread(() -> { double result = get(); completableFuture.complete(result); }).start(); System.out.println("=========main start no block=========="); completableFuture.whenComplete((v, t) -> { Optional.ofNullable(v).ifPresent(System.out::println); Optional.ofNullable(t).ifPresent(Throwable::printStackTrace); }); System.out.println("=========main end no block=========="); } private static double get() { try { Thread.sleep(RANDOM.nextInt(10000)); } catch (InterruptedException e) { e.printStackTrace(); } return RANDOM.nextDouble(); } }
Console Output
Note: completableFuture.whenComplete 是非阻塞的
<U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
package org.fool.java8.completable; import java.util.Optional; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; public class CompletableFutureTest2 { private final static Random RANDOM = new Random(System.currentTimeMillis()); public static void main(String[] args) throws ExecutionException, InterruptedException { AtomicBoolean finished = new AtomicBoolean(false); CompletableFuture.supplyAsync(CompletableFutureTest2::get).whenComplete((v, t) -> { Optional.ofNullable(v).ifPresent(System.out::println); Optional.ofNullable(t).ifPresent(Throwable::printStackTrace); finished.set(true); }); System.out.println("===========main start no block============"); while (!finished.get()) { System.out.println(Thread.currentThread().getName()); Thread.sleep(1000); } System.out.println("=========main end no block=========="); } private static double get() { try { Thread.sleep(RANDOM.nextInt(10000)); } catch (InterruptedException e) { e.printStackTrace(); } return RANDOM.nextDouble(); } }
Console Output
当把while那段代码注释掉
再次执行
Note: 这个方法启动的是一个daemon线程
<U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
package org.fool.java8.completable; import java.util.Optional; 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.atomic.AtomicBoolean; public class CompletableFutureTest3 { private final static Random RANDOM = new Random(System.currentTimeMillis()); public static void main(String[] args) throws ExecutionException, InterruptedException { AtomicBoolean finished = new AtomicBoolean(false); ExecutorService executorService = Executors.newFixedThreadPool(2, r -> { Thread t = new Thread(r); t.setDaemon(false); return t; }); CompletableFuture.supplyAsync(CompletableFutureTest3::get, executorService).whenComplete((v, t) -> { Optional.ofNullable(v).ifPresent(System.out::println); Optional.ofNullable(t).ifPresent(Throwable::printStackTrace); finished.set(true); }); System.out.println("===========main start no block============"); while (!finished.get()) { System.out.println(Thread.currentThread().getName()); Thread.sleep(1000); } System.out.println("=========main end no block=========="); } private static double get() { try { Thread.sleep(RANDOM.nextInt(10000)); } catch (InterruptedException e) { e.printStackTrace(); } return RANDOM.nextDouble(); } }
Console Output
Note: 使用ExecutorService默认线程是非Daemon线程,这里将线程显示设置为非Daemon线程,运行完毕,程序还是处于hold状态
相关推荐
在"ServerSocket_Hello_World-master"这个项目中,通常包含以下文件: - `Server`类:实现服务器端逻辑,创建`ServerSocket`,接收连接,发送“Hello, World!”消息,并处理客户端输入。 - `Client`类(可选):用于...
HelloWorldThread thread = new HelloWorldThread(); thread.start(); } } ``` 在Java 8中,除了基础的线程操作,还引入了`java.util.concurrent`包中的高级并发API,如`ExecutorService`、`Future`、`Callable`...
}).thenApply(s -> s + "World").join(); ``` **Stream API与并行流:** - **定义:** Java 8引入的新特性,用于操作集合对象。 - **并行流:** 通过并行的方式处理数据,提高处理效率。 **并发安全的集合类:**...
- **Akka实践**:通过HelloWorld示例,展示如何创建和交互Actor。 - **Actor的生命周期和管理**:包括Actor的创建、停止、消息传递和错误处理策略。 这个PPT教程覆盖了Java并发编程的广泛领域,从理论到实践,从...
这段代码创建了一个异步任务,先等待1秒,然后输出"Hello World"。 以上只是Java 8新增特性的一小部分介绍。通过学习这些新特性,开发者可以编写出更加高效、可读性强的代码。此外,《Java 8编程参考官方教程 第9版...
- **示例**:`var myVar = "Hello World";` 在这里,编译器会自动识别 `myVar` 的类型为 String。 - **优势**: - **减少冗余**:避免重复写出变量类型,使代码更简洁。 - **增强可读性**:变量类型由编译器推断...
}).thenApply(s -> s + " World").thenAccept(System.out::println); ``` 六、异步与并发策略 在实现线程异步时,还需要考虑并发策略,如同步机制(synchronized、Lock)、并发容器(ConcurrentHashMap、...
【标题】"JDK代码学习"涉及的是Java开发工具包(Java ...对于初学者,可以从简单的 HelloWorld 程序开始,逐步深入到并发编程、IO操作等复杂主题;对于有经验的开发者,了解JDK7的新特性将有助于提高代码质量和性能。
例如,`()->System.out.println("Hello, World!")`就是一个简单的Lambda表达式,表示无参数且返回值为空的方法。 2. **方法引用和构造器引用** 方法引用进一步扩展了Lambda表达式的使用,它允许我们直接引用已有...
例如,`Runnable` 接口可以用 `(()->System.out.println("Hello, World!"))` 这样的 Lambda 表达式来表示。开发者可以使用 Lambda 更方便地编写回调函数,提高代码的可读性和简洁性。 2. **Stream API**:Stream ...
例如,`Runnable r = () -> System.out.println("Hello, World!");` 这个lambda表达式可以替代传统的匿名内部类,使得代码更加简洁易读。 2. **Stream API**: Stream API提供了对集合操作的新方法,如filter、map...
message.setBody("Hello, World!"); connection.sendStanza(message); // 监听消息 PacketListener packetListener = new PacketListener() { @Override public void processPacket(Packet packet) { if (packet...