线程池在项目中的使用

1.runAsync执行完后无返回值

package com.search.thread;
import java.util.concurrent.*;
public class ThreadTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
        System.out.println("main......start.....");
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
        }, executor);
    }
}  

2.supplyAsync执行完后有返回值,后续能感知异常

package com.search.thread;
import java.util.concurrent.*;
public class ThreadTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
         /**
         * 方法完成后的处理
         */
       CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
             System.out.println("当前线程:" + Thread.currentThread().getId());
             int i = 10 / 0;
             System.out.println("运行结果:" + i);
             return i;
         }, executor).whenComplete((res,exception) -> {
             //虽然能得到异常信息,但是没法修改返回数据
             System.out.println("异步任务成功完成了...结果是:" + res + "异常是:" + exception);
         }).exceptionally(throwable -> {
             //可以感知异常,同时返回默认值
             return 10;
        });
    }
} 

3.supplyAsync执行完后有返回值,后续能感知异常

package com.search.thread;
import java.util.concurrent.*;
public class ThreadTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
        /**
         * 方法执行完后端处理
         */
         CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
             System.out.println("当前线程:" + Thread.currentThread().getId());
             int i = 10 / 2;
             System.out.println("运行结果:" + i);
             return i;
         }, executor).handle((result,thr) -> {
             if (result != null) {
                return result * 2;
             }
             if (thr != null) {
                 System.out.println("异步任务成功完成了...结果是:" + result + "异常是:" + thr);
                 return 0;
             }
             return 0;
         });
    }
} 

4.线程串行化,如:A任务执行完再执行B任务

线程池在项目中的使用_第1张图片

package com.search.thread;
import java.util.concurrent.*;
public class ThreadTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.thenRun开头的,不接受上一步(如:supplyAsync)的返回结果,thenRun执行完本身没有返回值
         CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
            return i;
        }, executor).thenRunAsync(()-> {
            System.out.println("任务2启动了...");
        },executor);

        // 2.thenAccept开头的,需要接受上一步(如:supplyAsync)的返回结果,thenAccept执行完本身也没有返回值
        CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
            return i;
        }, executor).thenAcceptAsync(res -> {
            System.out.println("任务2启动了..." + res);
        }, executor);

        // 3.thenApply开头的,需要上一步(如:supplyAsync)的返回结果,thenApply执行完本身最终会有返回值
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
            return i;
        }, executor).thenApplyAsync(res -> {
            System.out.println("任务2启动了..." + res);
            return "Hello" + res;
        }, executor);
    }
} 

5.两任务组合 - 如:A、B两任务都要完成再执行另一个任务C

线程池在项目中的使用_第2张图片
线程池在项目中的使用_第3张图片

package com.search.thread;
import java.util.concurrent.*;
public class ThreadTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

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

        // thenApply开头的,需要上一步(如:supplyAsync)的返回结果,thenApply执行完本身最终会有返回值
        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
            return i;
        }, executor).thenApplyAsync(res -> {
            System.out.println("任务2启动了..." + res);
            return "Hello" + res;
        }, executor);

        CompletableFuture<Integer> future02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
            return i;
        }, executor);
        
        //1.future01和future02执行完成后再执行自己的,不接受future01和future02的返回值,执行完自己的也没有返回值
        future01.runAfterBothAsync(future02,()->{
            System.out.println("任务3开始...");
        },executor);

        //2.future01和future02执行完成后再执行自己的,接受future01和future02的返回值,执行完自己的是没有返回值的
        future01.thenAcceptBothAsync(future02,(f1,f2)-{
           System.out.println("任务3开始...之前的返回结果:"+f1+"-->"+f2);
        },executor);
        
        //3.future01和future02执行完成后再执行自己的,接受future01和future02的返回值,执行完自己的是有返回值的
        CompletableFuture<String> future = future01.thenCombineAsync(future02, (f1, f2) ->(
               return f1 +":" + f2 +" -> Haha";
        },executor);
        System.out.println("main....end...."+future.get());


    }
} 

6.两任务组合 - 如:A、B两任务只要有一个完成就执行另一个任务C

线程池在项目中的使用_第4张图片
线程池在项目中的使用_第5张图片

package com.search.thread;
import java.util.concurrent.*;
public class ThreadTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

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

        // thenApply开头的,需要上一步(如:supplyAsync)的返回结果,thenApply执行完本身最终会有返回值
        CompletableFuture<Object> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
            return i;
        }, executor).thenApplyAsync(res -> {
            System.out.println("任务2启动了..." + res);
            return "Hello" + res;
        }, executor);

        CompletableFuture<Object> future02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
            return i;
        }, executor);
        
        //1.future01或future02有一个执行完成后再执行自己的任务,不接受future01和future02的返回值,执行完自己的也没有返回值
        future01.runAfterEitherAsync(future02,()->{
            System.out.println("任务3开始...");
        },executor);

        //2.future01或future02有一个执行完成后再执行自己的任务,接受future01和future02的返回值(返回类型要相同),执行完自己的是没有返回值的
        future01.acceptEitherAsync(future02,(res)->{
              System.out.printn("任务3开始...之前的结果:"+res);
        },executor);
        
        //3.future01或future02有一个执行完成后再执行自己的,接受future01和future02的返回值,执行完自己的是有返回值的
        CompletableFuture<String> future = future01.applyToEitherAsync(future02, res ->{
       		 System.out.println("任务3开始...之前的结果: + res");
       		 return res.toString() +"->哈哈"
        };executor)
        System.out.printIn("main....end..."+future .get());
    }
} 

7.多任务组合 - 等待全部完成和只要有一个任务完成

在这里插入图片描述
allOf:等待所有任务完成
anyOf:只要有一个任务完成

package com.search.thread;
import java.util.concurrent.*;
public class ThreadTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

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

        CompletableFuture<String> futureImg= CompletableFuture.supplyAsync(() -> {
     		   System.out.println("查询商品的图片信息");
      		   return "hello.jpg";
        });

       CompletableFuture<String> futureAttr = CompletableFuture.supplyAsync(() -> {
               System.out.printIn("查询商品的属性");
               return "黑色+256G";
        });
        
        CompletableFuture<String> futureDesc = CompletableFuture.supplyAsync(() -> {
              try {
                   Thread.sleep(3000);
                   System.out.println("查询商品介绍"); 
              }catch (InterruptedException e) {
                   e.printStackTrace();
              }
              return"华为";
         });


        CompletableFuture<Void> all0f = CompletableFuture.allof(futureImg, futureAttr, futureDesc);
        allof.get();//等待所有结果完成
        System.out.printIn("main,.,end...,"+futureImg.get()+"=>"+futureAttr.get()+"=>"+futureDesc.get());

        CompletableFuture<0bject> anyof = CompletableFuture.any0f(futureImg, futureAttr, futureDesc
        anyof.get();//等待所有结果完成
        System.out.printIn("main,.,end...,"+anyof.get());
    }
} 

你可能感兴趣的:(java,android,开发语言)