1.自定义线程池分类
- JUC提供的线程池: ThreadPoolExecutor类
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
1, 10, 60, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(10), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "my—thread-name-" + r.hashCode());
}
},new ThreadPoolExecutor.CallerRunsPolicy());
- spring提供的默认线程池:ThreadPoolTaskExecutor类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.*;
/**
* 配置线程池直接定义好线程的
*
*/
@Configuration
public class ThreadPoolConfig {
@Bean(name = "myTaskExecutor")
public Executor myTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池大小
executor.setCorePoolSize(1);
//最大线程数
executor.setMaxPoolSize(3);
//队列容量
executor.setQueueCapacity(2);
//活跃时间
executor.setKeepAliveSeconds(60);
//线程名字前缀
executor.setThreadNamePrefix("my—thread-name");
//线程池的饱和策略自定义 根据业务自己随意定义
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
2.线程池使用主要的参数
corePoolSize(线程池基本大小)
maximumPoolSize(线程池最大大小)
keepAliveTime(线程存活保持时间)
workQueue(任务队列)
threadFactory(线程工厂)
handler(线程饱和策略)
3.线程池饱和策略
AbortPolicy:直接抛出异常,默认策略
CallerRunsPolicy:用调用者所在线程来执行任务
DiscardOldestPolicy:丢弃阻塞队列中靠最前的任务,并执行当前任务
DiscardPolicy:直接丢弃当前任务
自定义,重要的不可丢弃的线程任务持久化,用补偿机制来再次执行
new ThreadPoolExecutor.AbortPolicy()
4.调用的异步方法
//Spring配置调用,池子已经默认
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
/**
* @Description Future可以用void替换,根据业务选择,需要返回值用Future
* @Date 16:58 2021/3/23
*/
@Component
public class Asyncs {
@Async
public Future<String> geta(int i) throws InterruptedException {
String s = Thread.currentThread().getName()+":测试"+i+"接口";
System.out.println(s);
return new AsyncResult<>(s);
}
}
//用池子来调用
@Autowired
private ThreadPoolTaskExecutor config;
@Test
void contextLoads() {
config.execute(new Runnable() {
@Override
public void run() {
System.out.println("直接用池子调用的");
}
});
}
未完。。。。。。