一、定义线程池
1、线程工厂使用了guava
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
2、自定义线程池代码
package com.gzgs.studydemo02.common.utils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.List;
import java.util.concurrent.*;
public class MyTestThreadPool {
//ThreadPoolExecutor是线程池的核心实现类,在JDK1.5引入,位于java.util.concurrent包
private ThreadPoolExecutor poolExecutor;
//饿汉式,单例模式
//第一步:将无参构造私有化
//第二步:在类中直接创建MyTestThreadPool对象
//第三步:提供getInstance()方法返回对象
private MyTestThreadPool(){//<--- 这是第一步
poolExecutor = new ThreadPoolExecutor(3,
5,
3,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(20),
new ThreadFactoryBuilder().setNameFormat("myTestThread-pool-%d").build(),//定义线程名称,自己自定义即可
new ThreadPoolExecutor.AbortPolicy());
}
private static final MyTestThreadPool myTestThreadPool = new MyTestThreadPool();//<--- 这是第二步
public static MyTestThreadPool getInstance(){//<--- 这是第三步
return myTestThreadPool;
}
//有回调方法
public Future<Object> submit(Callable<Object> task) throws Exception{
return poolExecutor.submit(task);
}
//单个处理任务
public void execute(Runnable task){
poolExecutor.execute(task);
}
// 批处理任务
public void execute(List<Runnable> tasks){
tasks.stream().forEach(task->poolExecutor.execute(task));
}
}
二、编程式事务TransactionTemplate
交给spring管理
@Autowired
private TransactionTemplate transactionTemplate;
代码列子如下:
Object execute = transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus transactionStatus) {
try {
//业务代码
} catch (Exception e) {
//手动事务回滚
//transactionStatus.setRollbackOnly();
//抛异常事务回滚
throw new RuntimeException(e);
}
return null;
}
});
三、线程池+编程式事务代码示例
@Override
public void transactionalTest() throws Exception{
MyTestThreadPool threadPool = MyTestThreadPool.getInstance();
int a =5;
for (int i=0;i<a;i++){
Thread.sleep(1000);//休眠,避免抢占资源导致死锁
threadPool.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
Object execute = transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus transactionStatus) {
try {
//业务代码
transactionalTestG((int)(Math.random()*5+1));
} catch (Exception e) {
//手动事务回滚
//transactionStatus.setRollbackOnly();
//抛异常事务回滚
throw new RuntimeException(e);
}
return null;//看自己业务需求,返回自己想要的
}
});
return null;//看自己业务需求,返回自己想要的
}
});
}
}
public void transactionalTestG(int i) throws Exception{
User user = new User();
user.setUserId(IdWorker.getId()).setAge(i).setUserName("用户名"+i);
userMapper.insert(user);
System.out.println(i);
try {
if(i==5){
int j =1/0;
}
}catch (Exception e){
System.out.println("i="+i+" 异常:"+e.getMessage());
throw e;
}
}