异步&线程池

一、线程

1.继承Thread

public static class Thread01 extends Thread{
	@Override
	public void run() {
	    System.out.println("当前线程:"+Thread.currentThread().getId());
	    int i = 10 / 2;
	    System.out.println("运行结果:"+i);
	}
}
//main方法中启动
Thread01 thread = new Thread01();
thread.start();//启动线程

2.实现Runnable接口

public static class Runnable01 implements Runnable{
	@Override
	public void run() {
	    System.out.println("当前线程:"+Thread.currentThread().getId());
	    int i = 10 / 2;
	    System.out.println("运行结果:"+i);
	}
}
//main方法启动
Runnable01 runnable01 = new Runnable01();
new Thread(runnable01).start();

3.实现Callable接口 + FutureTask (可以拿到返回结果,可以处理异常)

public static class Callable01 implements Callable<Integer>{

	@Override
	public Integer call() throws Exception {
	   System.out.println("当前线程:"+Thread.currentThread().getId());
	    int i = 10 / 2;
	    System.out.println("运行结果:"+i);
	    return i;
	}
}
//main方法启动
new Thread(futureTask).start();
//阻塞等待整个执行完成,返回结果
Integer integer = futureTask.get();

4.线程池(ExecutorService)

以后在业务代码中,以上三种开启线程方法均不使用,而是将【所有的多线程异步任务交给线程池来执行】
给线程池直接提交任务
/**
* 线程池七大参数
* corePoolSize 核心线程数,线程池创建好以后就准备就绪的线程数量,就等待接受异步任务去执行
* maximumPoolSize 线程池最大线程数量
* keepAliveTime 空闲线程存活时间
* unit 空间线程存活时间单位
* BlockingQueue 阻塞队列
* threadFactory 线程工厂
* handler 拒绝策略
*/

1、创建
1)、Executors
2)、new ThreadPoolExecutor

ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
       200,
        10,
        TimeUnit.SECONDS,
        new LinkedBlockingDeque<>(10000),
        Executors.defaultThreadFactory(),
        new ThreadPoolExecutor.AbortPolicy()
);

二、CompletableFuture异步编排

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值