知识点记录-高并发JAVA多线程(thread runnable callable executors future completablefuture)

26 篇文章 0 订阅
10 篇文章 0 订阅

知识点记录-高并发JAVA多线程(thread runnable callable executors future completablefuture)

package com.thread;

import java.util.concurrent.*;

//多线程,可用于优化业务功能流程执行效率 
public class JavaThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {

        //使用thread类
        Thread1 thread1 = new Thread1();
        thread1.start();

        Thread thread = new Thread1();
        thread.start();

        //runnable接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("使用runnable接口创建线程");
            }
        }).start();

        //使用runnable接口的lambda表达式
        new Thread(() -> {
            System.out.println("使用runnable接口的lambda表达式");
        }).start();

        //callable接口
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "使用callable接口创建线程";
            }
        };

        //创建线程池 多个功能使用多个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        ExecutorService executorService1 = new ThreadPoolExecutor(5, 50,
                5000L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(500),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        Future<String> future = executorService.submit(callable);
        System.out.println(future.get(5, TimeUnit.SECONDS));

        //callabe接口的lambda表达式
        System.out.println(executorService.submit(() -> "使用callabe接口的lambda表达式").get());

        //多线程流.JDK8接口CompletableFuture
        CompletableFuture completableFuture = new CompletableFuture();
        completableFuture.complete("完成completableFuture");
        System.out.println("返回值completableFuture.join=" + completableFuture.join());
        System.out.println("返回值completableFuture.get=" + completableFuture.get());

        //runAsync(没返回值)默认线程池ForkJoinPool.commonPool()
        CompletableFuture.runAsync(() -> {
            System.out.println("使用CompletableFuture.runAsync默认线程池ForkJoinPool.commonPool()");
        });

        //runAsync(没返回值) 指定线程池
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("使用CompletableFuture.runAsync指定线程池");
        }, executorService);
//        System.out.println("完成voidCompletableFuture.isDone=" + voidCompletableFuture.isDone());
//        System.out.println("返回值voidCompletableFuture.get=" + voidCompletableFuture.get());

        //supplyAsync (有返回值)
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("使用CompletableFuture.supplyAsync");
            return "使用CompletableFuture.supplyAsync";
        }, executorService);
        System.out.println("完成stringCompletableFuture.isDone=" + stringCompletableFuture.isDone());
        System.out.println("返回值stringCompletableFuture.get=" + stringCompletableFuture.get());

        CompletableFuture<String> stringCompletableFuture1 = CompletableFuture.supplyAsync(() -> "线程1");
        CompletableFuture<String> stringCompletableFuture2 = CompletableFuture.supplyAsync(() -> "线程2");

        //(有参有返回值) thenApply thenApplyAsync / (有参没返回值) thenAccept thenAcceptAsync/ (没参没返回值) thenRun thenRunAsync
        CompletableFuture<String> stringCompletableFuture3 = stringCompletableFuture1.thenApplyAsync((r1) -> "thenApply" + r1);
        System.out.println("返回值stringCompletableFuture3.get()=" + stringCompletableFuture3.get());

        CompletableFuture<Void> voidCompletableFuture1 = stringCompletableFuture1.thenAccept((r1) -> System.out.println("thenAccept" + r1));
        System.out.println("voidCompletableFuture1.get()=" + voidCompletableFuture1.get());

        CompletableFuture<Void> voidCompletableFuture2 = stringCompletableFuture1.thenRun(() -> System.out.println("thenRun"));
        System.out.println("voidCompletableFuture2.get()=" + voidCompletableFuture2.get());

        //thenCombine 有参有返回值 并行线程1与线程2,完成执行线程3
        CompletableFuture<String> stringCompletableFuture4 = stringCompletableFuture1.thenCombine(stringCompletableFuture2, (r1, r2) -> "thenCombine" + r1 + r2);
        System.out.println("stringCompletableFuture4.get=" + stringCompletableFuture4.get());

        //thenCompose 执行线程1 -> 使用线程1的返回值 -> 执行线程5
        CompletableFuture<String> stringCompletableFuture5 = stringCompletableFuture1.thenCompose(r1 -> CompletableFuture.supplyAsync(() -> "thenCompose" + r1));
        System.out.println("stringCompletableFuture5.get=" + stringCompletableFuture5.get());

        //whenComplete 完成或异常回调
        stringCompletableFuture1.whenComplete((result, exception) -> {
            if (exception != null) {
                System.out.println("whenComplete异常=" + exception);
            } else {
                System.out.println("whenComplete返回值=" + result);
            }
        });

        //handle 接收返回值,可修改
        CompletableFuture<String> stringCompletableFuture6 = stringCompletableFuture1.handle((result, exception) -> {
            if (exception != null) {
                return ("handle异常=" + exception);
            } else {
                return ("handle返回值=" + result);
            }
        });
        System.out.println("stringCompletableFuture6.get=" + stringCompletableFuture6.get());

        //exceptionally 异常回调
        CompletableFuture<Object> exceptionally = CompletableFuture.supplyAsync(() -> {
                            throw new RuntimeException("有异常");
                        }
                ).whenComplete((result, exception) -> {
                    if (exception != null) {
                        System.out.println("exceptionally whenComplete异常=" + exception);
                    } else {
                        System.out.println("exceptionally whenComplete返回值=" + result);
                    }
                })
                .exceptionally((exception) -> "exceptionally:" + exception);
        System.out.println("exceptionally.get=" + exceptionally.get());

        //thenAcceptBoth 有参没返回值 并行线程1与线程2,完成执行线程3
        CompletableFuture<Void> voidCompletableFuture3 = stringCompletableFuture1.thenAcceptBoth(stringCompletableFuture2, (r1, r2) -> System.out.println("thenAcceptBoth=" + r1 + r2));
        System.out.println("voidCompletableFuture3.get=" + voidCompletableFuture3.get());

        //runAfterBoth 没参没返回值 并行线程1与线程2,完成执行线程3
        CompletableFuture<Void> voidCompletableFuture4 = stringCompletableFuture1.runAfterBoth(stringCompletableFuture2, () -> {
            System.out.println("runAfterBoth");
        });
        System.out.println("voidCompletableFuture4.get=" + voidCompletableFuture4.get());

        //applyToEither 有参有返回值 线程1或线程2执行完成
        CompletableFuture<String> stringCompletableFuture7 = stringCompletableFuture1.applyToEither(stringCompletableFuture2, (r) ->
                "applyToEither " + r
        );
        System.out.println("stringCompletableFuture7.get=" + stringCompletableFuture7.get());

        //acceptEither 有参没返回值 线程1或线程2执行完成
        CompletableFuture<Void> voidCompletableFuture5 = stringCompletableFuture1.acceptEither(stringCompletableFuture2, (r) -> {
            System.out.println("acceptEither " + r);
        });
        System.out.println("voidCompletableFuture5.get=" + voidCompletableFuture5.get());

        //runAfterEither 没参没返回值 线程1或线程2执行完成
        CompletableFuture<Void> voidCompletableFuture6 = stringCompletableFuture1.runAfterEither(stringCompletableFuture2, () -> {
            System.out.println("runAfterEither");
        });
        System.out.println("voidCompletableFuture6.get=" + voidCompletableFuture6.get());

        //调用completeExceptionally
//        CompletableFuture completableFuture1 = new CompletableFuture();
//        CompletableFuture.supplyAsync(()->{
//          try {
//              int v = 1/0;
//          }catch (Exception  e)
//          {
//              completableFuture1.completeExceptionally(e);
//          }
//          return 0;
//        });
//        System.out.println("completeExceptionally completableFuture1.get=" + completableFuture1.get());

        //allOf
        CompletableFuture.allOf(stringCompletableFuture1, stringCompletableFuture2, stringCompletableFuture3).whenComplete((v, exception) -> {
            System.out.println("allOf");
        });

        //anyOf
        CompletableFuture.anyOf(stringCompletableFuture1, stringCompletableFuture2, stringCompletableFuture3).whenComplete((v, exception) -> {
            System.out.println("anyOf");
        });

        //CountDownLatch 类似allOf
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                countDownLatch.countDown();
                System.out.println("执行1 countDownLatch.getCount=" + countDownLatch.getCount());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                countDownLatch.countDown();
                System.out.println("执行2 countDownLatch.getCount=" + countDownLatch.getCount());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        countDownLatch.await(); //阻塞
        System.out.println("CountDownLatch");

        executorService.shutdown();
    }


    public static class Thread1 extends Thread {
        @Override
        public void run() {
            System.out.println("使用Thread类创建线程");
        }
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值