线程池ThreadPoolExecutor最全实战案例

线程池ThreadPoolExecutor

1、创建线程池 ThreadPoolExecutor()

  • corePoolSize:核心线程数[一直存在]。除非设置allowCoreThreadTimeOut,线程池创建以后准备就绪的线程数量。
  • maximumPoolSize:最大线程数量,控制资源。
  • keepAliveTime:存活时间。如果当前的线程数量大于核心线程数,只要线程空闲时间大于指定的keepAliveTime时间,就释放空闲的线程(maximumPoolSize-corePoolSize)。
  • TimeUnit:存活时间单位。
  • BlockingQueue:阻塞队列。如果任务很多,就会将多的任务放在队列中,只要有线程空闲,就会去队列中取出新的任务执行。
  • ThreadFactory:线程的创建工厂。
  • RejectedExecutionHandler:如果队列满了,按照指定的拒绝策略执行任务。

2、工作顺序

  • 1)、线程池创建,准备核心线程,准备接受任务;
  • 2)、新的任务进来,用空闲的核心线程执行任务;
  • 3)、核心线程满了,将再进来的任务放入阻塞队列中,空闲的核心线程会去阻塞队列中获取任务执行;
  • 4)、阻塞队列满了,就直接开启新线程执行,最大只能开到max设置的数量;
  • 5)、任务执行完成,空闲的线程(最大线程数-核心线程数)会在keepAliveTime指定的时间后自动销毁,最终保持到核心线程数量;
  • 6)、如果线程开到了最大线程数,还有新的任务进来,就会使用指定的拒绝策略进行处理。

3、拒绝策略

  • DiscardOldestPolicy:丢弃最老的任务;
  • CallerRunsPolicy:同步调用;
  • AbortPolicy:丢弃新任务并抛出异常;
  • DiscardPolicy:丢弃新任务;

4、CompletableFuture异步编排

CompletableFuture提供了四个静态方法创建异步任务:

CompletableFuture.runAsync(Runnable runnable);

CompletableFuture.runAsync(Runnable runnable,Executor executor);

CompletableFuture.supplyAsync(Supplier<U> supplier);

CompletableFuture.supplyAsync(Supplier<U> supplier,Executor executor);

其中runXXX没有返回结果,supplyXXX可以获取返回结果;

都可以传入自定义的线程池,否则使用默认的线程池;

1)、whenComplete可以处理正常和异常的计算结果,exceptionally处理异常情况。

whenComplete获取上任务的结果:

	public static void main(String[] args) {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).whenComplete((result,exception)->{
			System.out.println("异步任务完成了,结果:"+result);
			System.out.println("异步任务异常:"+exception);
		});
	}
// 执行结果:
-----main start--------1
当前线程12------当前结果5
异步任务完成了,结果:5
异步任务异常:null

whenComplete获取上任务抛出的异常信息:

	public static void main(String[] args) {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 0;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).whenComplete((result,exception)->{
			System.out.println("异步任务完成了,结果:"+result);
			System.out.println("异步任务异常:"+exception);
		});
	}
// 执行结果:
-----main start--------1
异步任务完成了,结果:null
异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero

exceptionally捕获异常信息,返回默认值

	public static void main(String[] args) throws Exception {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 0;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).whenComplete((result,exception)->{
			System.out.println("异步任务完成了,结果:"+result);
			System.out.println("异步任务异常:"+exception);
		}).exceptionally((exception)->{
			System.out.println("捕获异步任务异常:"+exception);
			return 10;
		});
		System.out.println("任务结果:"+future.get());
	}
// 执行结果:
-----main start--------1
异步任务完成了,结果:null
异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
捕获异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
任务结果:10

exceptionally可以捕获到whenComplete的异常

	public static void main(String[] args) throws Exception {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).whenComplete((result,exception)->{
			System.out.println("异步任务完成了,结果:"+result);
			System.out.println("异步任务异常:"+exception);
			throw new RuntimeException("whenComplete抛出异常");
		}).exceptionally((exception)->{
			System.out.println("捕获异步任务异常:"+exception);
			return 10;
		});
		System.out.println("任务结果:"+future.get());
	}
// 执行结果:
-----main start--------1
当前线程12------当前结果5
异步任务完成了,结果:5
异步任务异常:null
捕获异步任务异常:java.util.concurrent.CompletionException: java.lang.RuntimeException: whenComplete抛出异常
任务结果:10

exceptionally抛出异常,任务结束

	public static void main(String[] args) throws Exception {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).whenComplete((result,exception)->{
			System.out.println("异步任务完成了,结果:"+result);
			System.out.println("异步任务异常:"+exception);
			throw new RuntimeException("whenComplete抛出异常");
		}).exceptionally((exception)->{
			System.out.println("捕获异步任务异常:"+exception);
			throw new RuntimeException("任务执行失败");
		});
		System.out.println("任务结果:"+future.get());
	}
// 执行结果:
-----main start--------1
当前线程12------当前结果5
异步任务完成了,结果:5
异步任务异常:null
捕获异步任务异常:java.util.concurrent.CompletionException: java.lang.RuntimeException: whenComplete抛出异常
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.RuntimeException: 任务执行失败

whenComplete 和 whenCompleteAsync 区别:

  • whenComplete:使用当前任务的线程继续执行;
  • whenCompleteAsync:把whenCompleteAsync任务继续提交给线程池来进行执行;
  • whenComplete:可以获取异常信息,但不能处理异常;
  • exceptionally:可以获取异常信息,进行异常处理;

2)、handle方法执行完成后的处理,与complete一样,可处理异常,也可返回默认值

handle捕获异常,返回默认值

	public static void main(String[] args) throws Exception {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 0;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).handle((result,exception)->{
			System.out.println("异步任务完成了,结果:"+result);
			System.out.println("异步任务异常:"+exception);
			return 20;
		});
		System.out.println("任务结果:"+future.get());
	}
//执行结果:
-----main start--------1
异步任务完成了,结果:null
异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
任务结果:20

handle抛出异常,任务结束

	public static void main(String[] args) throws Exception {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 0;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).handle((result,exception)->{
			System.out.println("异步任务完成了,结果:"+result);
			System.out.println("异步任务异常:"+exception);
			throw new RuntimeException("handle抛出异常");
		});
		System.out.println("任务结果:"+future.get());
	}
//执行结果:
-----main start--------1
异步任务完成了,结果:null
异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.RuntimeException: handle抛出异常

3)、线程串行化方法

线程串行化thenRun():不能获取到上一步任务的执行结果,不能捕获上一步异常,上一步异常任务结束

	public static void main(String[] args) throws Exception {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture.supplyAsync(() -> {
			int a = 10 / 0;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).thenRun(()->{
			System.out.println("任务2启动了");
		});
		System.out.println("任务结果:");
	}
// 执行结果:
-----main start--------1
任务结果:

线程串行化thenRun():不能获取到上一步任务的执行结果,无返回值

	public static void main(String[] args)  {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).thenRun(()->{
			System.out.println("任务2启动了");
		});
		System.out.println("任务结果:");
	}
// 执行结果:
-----main start--------1
当前线程12------当前结果5
任务2启动了
任务结果:

线程串行化thenRun():不能获取到上一步任务的执行结果,无返回值,发生异常时不会抛出异常

	public static void main(String[] args)  {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).thenRun(()->{
			System.out.println("任务2启动了");
			throw new RuntimeException("任务2失败了");
		});
		System.out.println("任务结果:");
	}
// 执行结果:
-----main start--------1
当前线程12------当前结果5
任务2启动了
任务结果:

线程串行化thenAccept():可以获取上一步结果,异常与thenRun()方法一致

	public static void main(String[] args)  {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).thenAccept((result)->{
			System.out.println("任务1执行结果"+result);
			System.out.println("任务2启动了");
			throw new RuntimeException("任务2失败了");
		});
		System.out.println("任务结果:");
	}
//执行结果:
-----main start--------1
当前线程12------当前结果5
任务1执行结果5
任务2启动了
任务结果:

线程串行化thenAccept():可以获取上一步结果,异常与thenRun()方法一致

	public static void main(String[] args)  {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
			return a;
		}).thenAccept((result)->{
			System.out.println("任务1执行结果"+result);
			System.out.println("任务2启动了");
			throw new RuntimeException("任务2失败了");
		});
		System.out.println("任务结果:");
	}
//执行结果:
-----main start--------1
当前线程12------当前结果5
任务1执行结果5
任务2启动了
任务结果:

线程串行化thenApply():可以获取上一步结果,有返回值

public static void main(String[] args)  {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程" + Thread.currentThread().getId() + "------当前结果" + a);
			return a;
		}).thenApply((result) -> {
			System.out.println("任务1执行结果" + result);
			System.out.println("任务2启动了");
			return 100;
		});
		Integer result=null;
		try {
			result = future.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("任务结果:"+result);
	}
//执行结果:
-----main start--------1
当前线程12------当前结果5
任务1执行结果5
任务2启动了
任务结果:100

线程串行化thenApply():可以获取上一步结果,有返回值,可抛出异常,上一步发生异常任务结束

	public static void main(String[] args)  {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程" + Thread.currentThread().getId() + "------当前结果" + a);
			return a;
		}).thenApply((result) -> {
			System.out.println("任务1执行结果" + result);
			System.out.println("任务2启动了");
			throw new RuntimeException("任务2发生异常了");
		});
		Integer result=null;
		try {
			result = future.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("任务结果:"+result);
	}
//执行结果:
-----main start--------1
当前线程12------当前结果5
任务1执行结果5
任务2启动了
任务结果:null
java.util.concurrent.ExecutionException: java.lang.RuntimeException: 任务2发生异常了

thenApply 、thenAccept、thenRun 区别:

  • thenApply:当一个线程依赖另一个线程时,获取上一个任务返回的结果,并返回当前任务的返回值;
  • thenAccept:消费处理结果。接收任务处理的结果,并消息处理,无返回结果;
  • thenRun:只要上面的任务执行完成,就开始执行thenRun,只是处理完任务后,执行thenRun的后续操作;

4)、两任务组合,都要完成

runAfterBoth()无返回结果:任务1和任务2执行完成,执行当前任务;任务1和任务2任一抛出异常,任务3不执行;任一任务不会抛出异常;

	public static void main(String[] args)  {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程" + Thread.currentThread().getId() + "------任务一结果:" + a);
			return a;
		});

		CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 0;
			System.out.println("当前线程" + Thread.currentThread().getId() + "------任务二结果:" + a);
			return a;
		});

		future1.runAfterBoth(future2,()->{
			int a=1/0;
			System.out.println("任务三开始了"+a);
		});

		System.out.println("任务结果:");
	}
//执行结果:
-----main start--------1
当前线程12------任务一结果:5
任务结果:

runAfterBoth()无返回结果,可得到任务1和任务2结果:任务1和任务2任一抛出异常,任务3不执行;任一任务不会抛出异常;

	public static void main(String[] args)  {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程" + Thread.currentThread().getId() + "------任务一结果:" + a);
			return a;
		});

		CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程" + Thread.currentThread().getId() + "------任务二结果:" + a);
			return a;
		});

		future1.thenAcceptBothAsync(future2,(f1,f2)->{
			System.out.println("任务一结果:"+f1+"---任务二结果:"+f2);
			int a=1/0;
			System.out.println("任务三开始了"+a);
		});

		System.out.println("任务结果:");
	}
-----main start--------1
当前线程12------任务一结果:5
当前线程12------任务二结果:5
任务结果:
任务一结果:5---任务二结果:5

runAfterBoth()有返回结果,可得到任务1和任务2结果:任务1和任务2任一抛出异常,任务3不执行;可捕获任务3的异常;

	public static void main(String[] args)  {
		System.out.println("-----main start--------"+Thread.currentThread().getId());
		CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程" + Thread.currentThread().getId() + "------任务一结果:" + a);
			return a;
		});

		CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
			int a = 10 / 2;
			System.out.println("当前线程" + Thread.currentThread().getId() + "------任务二结果:" + a);
			return a;
		});

		CompletableFuture<Integer> future = future1.thenCombineAsync(future2, (f1, f2) -> {
			System.out.println("任务一结果:" + f1 + "---任务二结果:" + f2);
			int a = 1 / 0;
			System.out.println("任务三开始了" + a);
			return a;
		});

		Integer integer = null;
		try {
			integer = future.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("任务结果:"+integer);
	}
-----main start--------1
当前线程12------任务一结果:5
当前线程12------任务二结果:5
任务一结果:5---任务二结果:5
任务结果:null
java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero

thenCombine 、thenAcceptBoth、runAfterBoth 区别:

  • thenCombine:组合两个future,获取两个future的返回结果,并返回当前任务的返回值;
  • thenAcceptBoth:组合两个future,获取两个future任务的返回结果,然后处理任务,没有返回值;
  • runAfterBoth:组合两个future,不需要获取future的结果,只需要两个future处理完任务后,处理该任务;

5)、两任务组合,一个完成

applyToEither 、acceptEither、runAfterEither 区别:

  • applyToEither:两个任务有一个执行完成,获取它的返回值,处理任务并有新的返回值;
  • acceptEither:两个任务有一个执行完成,获取它的返回值,处理任务,没有新的返回值;
  • runAfterEither:两个任务有一个执行完成,不需要获取future的结果,处理任务,也没有返回值;

6)、多任务组合

allOf 、anyOf 区别:

  • allOf:等待所有任务完成
  • anyOf:只要有一个任务完成
原文地址:https://www.cnblogs.com/kevin-ying/p/14383380.html