线程串行化方法

单任务

这个些是无法感知Completablefuturec的返回结果的,这里前一个线程任务必须是Completablefuturec

//这个些是无法感知Completablefuturec的返回结果的,这里前一个线程任务必须是Completablefuturec
//public Completionstage thenRun (Runnable action);//没有加Async采用当前线程执行接下来的任务
//public Completionstage thenRunAsync (Runnable action);//采用Async就使用新的线程执行接下来的任务
//public Completionstage thenRunAsync (Runnable action, Executor executor);//采用Async就使用新的线程执行接下来的任务,并且指定线程来执行任务


  		CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            return i;
        },executorService).thenRunAsync(()->{
            System.out.println("任务2启动");
            System.out.println("当前线程ID-->" + Thread.currentThread().getId());
        },executorService);

这个可以感知Completablefuturec的返回结果的Consumer super就是上一个Completablefuture的执行结果action代表接下来处理的任务

//这个可以感知Completablefuturec的返回结果的Consumer super就是上一个Completablefuture的执行结果action代表接下来处理的任务
//public Completionstage thenAccept (Consumer < ? super T > action);
//public Completionstage thenAcceptAsync(Consumer < ? super T > action);
//public Completionstage thenAcceptAsync (Consumer < ? super T > action, Executor executor);

        CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            return i;
        },executorService).thenAcceptAsync(res->{
            System.out.println("当前线程ID-->" + Thread.currentThread().getId());
            System.out.println("任务2启动");
            System.out.println(res);
        },executorService);

这个不但能感知上个线程任务结束的返回值,还能在自己当前任务结束后同样带有返回值出去,

//这个不但能感知上个线程任务结束的返回值,还能在自己当前任务结束后同样带有返回值出去,
// T就是接收上个任务的返回值,U就是自己任务结束后返回出去的值,fn就是自己要处理的任务
//public   Completablefuture thenApply (Functionc ? super T,? extends Us fn)
//public  CompletableFuturec thenApplyAsync(Function ? super T, ? extends Us fn)
//public  Completablefuturec thenApplyAsync(Functionc ? super T, ? extends U > fn, Executor executor)
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            return i;
        }, executorService);
        future.thenApplyAsync(res->{
            System.out.println("当前线程ID-->" + Thread.currentThread().getId());
            System.out.println("任务2启动");
            System.out.println(res);
            return 10;
        },executorService);
        System.out.println(future.get());

两任务组合-都要完成

当任务1和任务2执行完成后执行任务3,但是任务3只能感知任务1、任务2任务执行完毕,无法得到结果

 		CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务1,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            return i;
        }, executorService);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务2,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 2;
            return i;
        }, executorService);


        future1.runAfterBothAsync(future2, () -> {
            System.out.println("当前任务3,线程ID-->" + Thread.currentThread().getId());
        }, executorService);

当任务1、任务2执行完毕后,任务三能感知到任务1、任务2执行完毕,并且还能得到返回值–但是任务3无法返回值

  		CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务1,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            return i;
        }, executorService);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务2,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 2;
            return i;
        }, executorService);

        future1.thenAcceptBothAsync(future2,(f1,f2)->{
            System.out.println("当前任务3,线程ID-->" + Thread.currentThread().getId());
            System.out.println("任务1返回值:"+f1);
            System.out.println("任务2返回值:"+f2);
        },executorService);

当任务1、任务2执行完毕后,任务3能感知,并且能的带任务1、任务2的值,任务3还能自己返回值出去

     CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务1,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            return i;
        }, executorService);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务2,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 2;
            return i;
        }, executorService);

        CompletableFuture<Integer> future3 = future1.thenCombineAsync(future2, (f1, f2) -> {
            System.out.println("当前任务3,线程ID-->" + Thread.currentThread().getId());
            System.out.println("任务1返回值:"+f1);
            System.out.println("任务2返回值:"+f2);
            return f1 + f2;
        }, executorService);

        System.out.println(future3.get());

两任务组合-其中一个完成即可

只能感知到任务结束,无法感知两个任务的执行结果

  		CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务1,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            return i;
        }, executorService);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务2,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 2;
            return i;
        }, executorService);
        
		future1.runAfterEitherAsync(future2,()->{
		    System.out.println("当前任务3,线程ID-->" + Thread.currentThread().getId());
		},executorService);

感知两个任务中先执行完的任务的执行结果

		CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务1,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            return i;
        }, executorService);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务2,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 2;
            return i;
        }, executorService);
		future1.acceptEitherAsync(future2,(res)->{
            System.out.println("当前任务3,线程ID-->" + Thread.currentThread().getId());
            System.out.println("得到其中的一个返回值"+res);
        },executorService);

感知两个任务中先执行完的任务的执行结果,并且可以返回值出去

		CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务1,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            return i;
        }, executorService);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务2,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 2;
            return i;
        }, executorService);
        
         CompletableFuture<Integer> future3 = future1.applyToEitherAsync(future2, (res) -> {
            System.out.println("当前任务3,线程ID-->" + Thread.currentThread().getId());
            System.out.println("得到其中的一个返回值" + res);
            return res + 10;
        }, executorService);
        System.out.println(future3.get());

多任务组合

等待任务全部执行完毕,这里的任务都是并行执行的

		System.out.println("主线程开始");
        long t1=new Date().getTime();
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务1,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return i;

        }, executorService);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务2,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 2;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return i;
        }, executorService);

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务3,线程ID-->" + Thread.currentThread().getId());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i = 10 / 5;
            return i;
        }, executorService);

        CompletableFuture<Void> conformityF = CompletableFuture.allOf(future1, future2, future3);
        conformityF.get();//等待所有任务执行完成

        System.out.println("任务1返回值-->"+future1.get());
        System.out.println("任务2返回值-->"+future2.get());
        System.out.println("任务3返回值-->"+future3.get());
        System.out.println(new Date().getTime()-t1);
        System.out.println("主线程结束");

等待任意一个任务执行完毕后结束

		System.out.println("主线程开始");
        long t1=new Date().getTime();
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务1,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 1;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return i;

        }, executorService);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务2,线程ID-->" + Thread.currentThread().getId());
            int i = 10 / 2;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return i;
        }, executorService);

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前任务3,线程ID-->" + Thread.currentThread().getId());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i = 10 / 5;
            return i;
        }, executorService);

        CompletableFuture<Object> conformityF = CompletableFuture.anyOf(future1, future2, future3);
        conformityF.get();//等待所有任务执行完成
        System.out.println("第一个执行完成的返回值-->"+conformityF.get());//那么这里拿到的就是第一个任务的返回值
        System.out.println(new Date().getTime()-t1);
        System.out.println("主线程结束");

实际场景

 @Override
    public String doPost(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        Out.debug("---------------获取关注状态-拉黑状态----------------");
        String userId=params.getString("userId");
        String tagId=params.getString("tagId");
        CompletableFuture<Integer> t1 = CompletableFuture.supplyAsync(() -> {
            return UserFollowDB.getCountByUid(userId,tagId);//是否是关注0.是未关注 1.是关注
        });

        CompletableFuture<Integer> t2 = CompletableFuture.supplyAsync(() -> {
            return  UserBlacklistDB.getCountByUserId(userId, tagId) == true ? 1 : 0;//是否是黑0.没拉黑 1.拉黑
        });

        CompletableFuture<JSONObject> t3 = t1.thenCombineAsync(t2, (f1, f2) -> {
            JSONObject res = new JSONObject();
            res.put("isAttention", f1);
            res.put("isBlock", f2);
            return res;
        });
        JSONObject res=null;
        try {
            res=t3.get();
        } catch (InterruptedException e) {
            return error(ErrorCodeList.SERVER_ERROR);
        } catch (ExecutionException e) {
            e.printStackTrace();
            return error(ErrorCodeList.SERVER_ERROR);
        }
        return success(res);
    }

这个接口是获取用户A,用户B之间是否关注,是否拉黑的,由于关注、拉黑操作需要入两次数据库,一般写法就是先查关注、在往下执行查询是否拉黑,那么假设关注查询需要100毫秒、拉黑查询也需要100毫秒,那么这样没做任何处理的话就需要200毫秒,那么我们使用任务编排后,只需要100毫秒即可执行完成!!!

你可能感兴趣的:(JAVA,多线程)