Java 线程池基础

整体内容

/*
Thread Pools
Executors
Callable and Future interfaces
Asynchronous Programming
Completable Futures
*/

Start

        var executor= Executors.newFixedThreadPool(2);
        System.out.println(executor.getClass().getName());
        try{
            for(int i=0;i<10;i++) {
                executor.submit(() -> {
                    System.out.println(Thread.currentThread().getId());
                });
            }
        }finally {
            executor.shutdown();//关闭线程池内线程
        }

submit返回值get方法

        var executor1= Executors.newFixedThreadPool(2);
        try{
            var future=executor1.submit(() -> {
                Thread.sleep(5000);
                return 1;
            });
            System.out.println("submit over");
            try{
                var result=future.get();//get方法是一个阻塞方法,线程没有返回时一直等待
                System.out.println(result);
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }finally {
            executor1.shutdown();//关闭线程池内线程
        }

Completable Futures

        //没有返回值
        Runnable task=()->{System.out.println("a");};
        var fut= CompletableFuture.runAsync(task);
        //有返回值
        Supplier<Integer>task1=()->{return  1;};
        var fut1=CompletableFuture.supplyAsync(task1);
        try {
            System.out.println(fut1.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

Implementing an Asynchronous API 创建异步API 异步编程*/

        MailService mailService=new MailService();
        mailService.sendAsync();
        mailService.sendAsync();
        System.out.println("haha");//haha 比 Mail was sent先输出
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

Running Code on Completion 异步完成后要执行些什么

        var fut_dcc=CompletableFuture.supplyAsync(()->1);
        fut_dcc.thenRun(()->System.out.println("Done"));//在些主线程上执行
        fut_dcc.thenRunAsync(()->System.out.println("Done"));//其他线程执行
        fut_dcc.thenAccept((result)->{System.out.println(result);});//接收返回参数

Handing Exceptions 异步程序执行时抛出异常怎么办

        var fut_nhg=CompletableFuture.supplyAsync(()->{
           throw new IllegalStateException();//一场并不会影响主线程
        });
        try {
            System.out.println(fut_nhg.exceptionally(ex->1).get());//有异常时将会返回1
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

Transforming Results

        var fut_fvdb=CompletableFuture.supplyAsync(()->20);
        //var result=fut_fvdb.thenApply(celsius->(celsius*1.8)+32).get();
        fut_fvdb.thenApply(celsius->(celsius*1.8)+32).thenAccept(System.out::println);

Composing Completable Futures 转换结果

        var fut_vfdv=CompletableFuture.supplyAsync(()->"email");
        fut_vfdv
                .thenCompose(email->CompletableFuture.supplyAsync(()->"playlist"))
                .thenAccept(playlist->System.out.println(playlist));

Combining Completable Futures

        var fut_first=CompletableFuture.supplyAsync(()->20);
        var fut_second=CompletableFuture.supplyAsync(()->0.9);
        fut_first
                .thenCombine(fut_second,(price,exchangeRate)->price*exchangeRate)
                .thenAccept(result->System.out.println(result));//18

waiting for Many tasks

        var fut_1=CompletableFuture.supplyAsync(()->1);
        var fut_2=CompletableFuture.supplyAsync(()->2);
        var fut_3=CompletableFuture.supplyAsync(()->3);
        var all=CompletableFuture.allOf(fut_1,fut_2,fut_3);
        all.thenRun(()->{
            try {
                var Result1=fut_1.get();
                System.out.println(Result1);//1
                var Result2=fut_2.get();
                var Result3=fut_3.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });

Waiting for the First Task

        var fut_a=CompletableFuture.supplyAsync(()->{
            for(int i=0;i<10000;){i++;}
            return 20;
        });
        var fut_b=CompletableFuture.supplyAsync(()->10);
        CompletableFuture.anyOf(fut_a,fut_b)
                .thenAccept(temp->System.out.println(temp));//all ways 20

Handing Timeouts

        var fut_g=CompletableFuture.supplyAsync(()->{
           for(int i=0;i<999999;){i++;}
           return 1;
        });
        try {
            var result=fut_g
                    .completeOnTimeout(1,1, TimeUnit.SECONDS)
                    .get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

MailService Class

class MailService{
    public void send(){
        for(int i=0;i<100000;){i++;}
        System.out.println("Mail was sent");
    }
    public CompletableFuture<Void>sendAsync(){
        return CompletableFuture.runAsync(()->send());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高万禄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值