Java 线程池基础

Posted 11biscuits

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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());
    }
}

以上是关于Java 线程池基础的主要内容,如果未能解决你的问题,请参考以下文章

Java线程池详解

Java 线程池详解

Java线程池详解

newCacheThreadPool()newFixedThreadPool()newScheduledThreadPool()newSingleThreadExecutor()自定义线程池(代码片段

阶段1 语言基础+高级_1-3-Java语言高级_05-异常与多线程_第5节 线程池_2_线程池的代码实现

IDEA对新建java线程池的建议