栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

异步运行理解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

异步运行理解

异步(我的理解):
  1:有多个线程同时执行,一个线程执行(main)当执行到一个地方,与此同时另一个线程开始执行,两者同一时刻都在运行,最后main线程把其他线程得结果返回。如果需要一个线程等待另一个线程执行完成可以使用CountDownLatch。
  2:有多个线程同时执行,一个线程执行(main),先把需要异步执行得代码跳过直接执行后面得代码不会等待其他线程执行完,于此同时其他线程也在执行需要异步的代码。

第一种例子:

public class DataController {

    public static void main(String[] args) {
        try {
            st();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    public static void st() throws Throwable, ExecutionException {
        // 两个线程的线程池
        ExecutorService executor = Executors.newFixedThreadPool(2);
        //jdk1.8之前的实现方式
        CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() {
            @Override
            public String get() {
                System.out.println("task started!"+"--"+Thread.currentThread().getName());
                try {
                    //模拟耗时操作
                    longTimeMethod();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "task finished!";
            }
        }, executor);

        //采用lambada的实现方式
        //future.thenAccept(e -> System.out.println(e + " ok"));
        future.thenAccept(a-> System.out.println(a+"hhaha"+Thread.currentThread().getName()));

        System.out.println("main thread is running");
    }

    public static void longTimeMethod(){
      int i = 10;
        try {
            Thread.sleep(60000);
            while (i > 7){
                i--;
                System.out.println("脸脸big eges"+Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}

第二种:之前惠生活业务写过之后补充

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/713091.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号