线程创建
lambda表达式形式
@Test public void myThreadTest(){ new Thread(()->{ System.out.println("hello myThread!!"); }).start(); }
重写runnable()方法
@Test public void threadTest(){ Runnable runnable = new Runnable() { @Override public void run() { System.out.println("hellow runnable!!"); } }; new Thread(runnable).start(); }
线程池创建
在config中创建,并使用@Bean注解进行容器管理
@Configuration @EnableAsync public class TaskPoolConfig { @Bean public Executor asyncExecutor() { Runtime runtime = Runtime.getRuntime(); ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); // 设置核心线程数为CPU核心数 taskExecutor.setCorePoolSize(runtime.availableProcessors()); // 设置最大线程数为CPU核心数两倍 taskExecutor.setMaxPoolSize(runtime.availableProcessors() * 2); // 阻塞队列长度 taskExecutor.setQueueCapacity(200); // 空闲线程存活时间 taskExecutor.setKeepAliveSeconds(60); // 线程名称前缀 taskExecutor.setThreadNamePrefix("taskExecutor--"); // 设置是否在关机时等待计划任务完成,不中断正在运行的任务并执行队列中的所有任务。 taskExecutor.setWaitForTasksToCompleteOnShutdown(true); // 设置此执行程序在关闭时应该阻止的最大秒数。 taskExecutor.setAwaitTerminationSeconds(60); return taskExecutor; } }
可通过 @Bean("asyncExecutor") 来指定注入时的线程池名字,否则默认类名asyncExecutor。
线程池任务提交
首先注入之前定义的线程池:
@Autowired private Executor asyncExecutor;
asyncExecutor.execute( ()->{ //这里写需要处理的业务 } )
通过execute()方法重写Runnable()将任务提交到线程池,这里为Lambda表达式形式。
线程同步工具CountDownLatch
线程同步工具CountDownLatch的使用主要有三部分组成:
// 线程同步工具 final CountDownLatch latch = new CountDownLatch();
首先定义线程同步工具。
// 线程同步工具数-1 latch.countDown();
再每一个子线程执行完毕后加入 latch.countDown(); 以统计有多少线程还在执行。
latch.await();
待子线程全部完成,继续向下执行。(需要进行异常处理)
@EnableAsync
在线程池定义的类上添加或在springBoot的启动类上添加,使用@EnableAsync来开启异步的支持(见上面的代码)
@async
在对应的方法上添加,向指定的线程池提交任务
@Component @Slf4j public class Task { @Async public void task(){ log.info("当前线程为:{}",Thread.currentThread().getName()); } }
可自定义执行器并指定例如:@Async("otherExecutor")