创建线程的七种方式:
继承Thread类
实现Runnable接口
匿名内部类的方式
带返回值的线程
定时器
线程池的实现
spring实现多线程
Lambda表达式实现
继承Thread以及实现Runnable这两种常见的方式就再说了,来总结下其他的实现方式。
带返回值的线程.可以实现Callable 泛型接口,这个接口只有一个call方法,用于设置返回的参数类型。
定时器创建线程:这种方式是使用定时器类来创建的。 定时执行一个任务,内部会执行线程。
线程池的实现
主要是使用线程池来创建线程 下面是创建一个无界线程池。
在spring中实现多线程
Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程的 可使用ThreadPoolTaskExecutor来实现基于线程池的TaskExecutor
在实际开发中由于多是异步,所以使用@EnableAsync来支持异步任务,且要在Bean的方法中使用@Async来声明其是一个异步任务。
代码实现
配置类taskexecutorconfig代码
package com.zxy.taskexecutor;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@ComponentScan("com.zxy.taskexecutor")
@EnableAsync //开启对异步任务的支持
public class TaskExecutorConfig implements AsyncConfigurer {
/**
* 通过实现AsyncConfigurer接口,重写getAsyncExecutor()方法,
* 返回一个ThreadPoolTaskExecutor对象,这样实现一个基于线程池
* TaskExecutor
*/
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(20);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
2.任务执行类asynctaskservice代码
package com.zxy.taskexecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {
@Async //声明是一个异步方法
public void executeAsyncTaskOne(int i){
System.out.println("执行异步任务: "+i);
}
@Async
public void executeAsyncTaskTwo(int i){
System.out.println("执行异步任务加1操作:"+(i+1));
}
}
3.运行
package com.zgw.taskexecutor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestExecutor {
public static void main(String[] args) {
//使用AnnotationConfigApplicationContext作为spring容器,
//接收输入一个配置类作为参数
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
//获得声明配置的AsyncTaskService的Bean
AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
for(int i =0 ;i<20;i++){
asyncTaskService.executeAsyncTaskOne(i);
asyncTaskService.executeAsyncTaskTwo(i);;
}
context.close();
}
}
Lambda表达式实现
实现求和(并行执行的加法运算)
尊重原创,受益匪浅。链接 blog.csdn.net/qq_37909508…