先来一段代码
Console.WriteLine("我是主");
Task.Run(() =>
{
Thread.Sleep(2000);
Console.WriteLine("我是异步");
});
Console.WriteLine("我是结束");
>>我是主
我是结束
我是异步
这是.NET 实现 JAVA怎么弄呢?
java有两种实现方式 @Async和 CompletableFuture
@Async
-
@Async 基于注解方法 比较方便
-
注意:启动类要加上 @EnableAsync
@Async public void asyncMethods() throws InterruptedException { Thread.currentThread().sleep(2000); System.out.println("我是异步"); }
CompletableFuture
-
无返回值
CompletableFuture.runAsync(() -> System.out.println("我是异步")); -
有返回值
CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{ return "我是异步"; }); future.get() -
阻塞两种方式
-
join() 会抛出 unchecked exception
-
get() 抛出 checked exception 必须用 try-catch 包裹
-
并行
List<CompletableFuture<String>> futures=new ArrayList<>(); for (int i = 0; i <8 ; i++) { int finalI = i; futures.add(CompletableFuture.supplyAsync(()->{ System.out.println("我是异步"+ finalI); return "我是异步"+ finalI; })); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); -
说到并行 JDK 8 还提供了遍历并行
List<Integer> list= Arrays.asList(1,2,3,4,5); list.parallelStream().forEach(x -> { try { Thread.sleep(1000); } catch (InterruptedException e) { } System.out.println(x); });