【面试:并发篇39:多线程:线程池】ThreadPoolExecutor类-提交、停止

【面试:并发篇39:多线程:线程池】ThreadPoolExecutor类-提交、停止

00.前言

如果有任何问题请指出,感谢。

01.提交任务

// 执行任务
	void execute(Runnable command);
	
	// 提交任务 task,用返回值 Future 获得任务执行结果
	<T> Future<T> submit(Callable<T> task);
	
	// 提交 tasks 中所有任务
	<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
	 throws InterruptedException;
	 
	// 提交 tasks 中所有任务,带超时时间
	<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
	 long timeout, TimeUnit unit)
	 throws InterruptedException;
	 
	// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消
	<T> T invokeAny(Collection<? extends Callable<T>> tasks)
	 throws InterruptedException, ExecutionException;
	 
	// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消,带超时时间
	<T> T invokeAny(Collection<? extends Callable<T>> tasks,
	 long timeout, TimeUnit unit)
	 throws InterruptedException, ExecutionException, TimeoutException;

submit方法

submit方法与execute方法的区别在于,execute方法接收的参数是Runnable类型的参数 没有返回值,而submit方法接收的是Callable类型的参数有返回值 且 返回值用Future<>接收,Future<>获取线程的返回值 实现原理 就是之前所讲的保护性暂停模式。
例子

@Slf4j(topic = "c.TestPool1")
public class TestPool1 {
   
    public static void main(String[] args) throws ExecutionException, InterruptedException {
   
        ThreadPoolExecutor threadpool=new ThreadPoolExecutor(2, 10,
                20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        Future<String> future = threadpool.
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

I cream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值