自定义线程池
@Configuration
public class myThreadPoolExecutor {
/***
* 7个参数:
* 1、核心线程
* 2、最大线程数
* 3、多于核心线程数的空闲线程数的存活时间
* 4、时间单位
* 5、阻塞队列
* 6、线程工厂名字
* 7、拒绝策略
* @return
*/
@Bean
public ThreadPoolExecutor myThreadPool(){
int corePoolSize = 4;
int maximumPoolSize = 8;
long keepAliveTime = 30;
TimeUnit unit = TimeUnit.SECONDS;
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
new LinkedBlockingDeque<>(10));
return threadPoolExecutor;
}
}
CountDownLatch案例
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
final int N = 10;
CountDownLatch countDownLatch = new CountDownLatch(N);
for (int i = 1; i <= N; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"号同学离开教室了");
countDownLatch.countDown();
}
});
thread.setName(String.valueOf(i));
thread.start();
}
countDownLatch.await();
System.out.println("教室锁门啦!!!");
}
}
CyclicBarrier案例
public class CyclicBarrierDemo {
public static void main(String[] args) {
final int N = 10;
CyclicBarrier cyclicBarrier = new CyclicBarrier(N, new Runnable() {
@Override
public void run() {
System.out.println("裁判响起发令枪!!!");
}
});
for (int i = 0; i < N; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+"号运动员准备好了");
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName()+"号运动员出发");
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
});
thread.setName(String.valueOf(i));
thread.start();
}
}
}
CompletableFuture手动事务控制
@RequiredArgsConstructor
@Slf4j
@Service
public class CompletableFutureTransactionalService {
private ThreadPoolExecutor myThreadPool;
private DataSourceTransactionManager dataSourceTransactionManager;
private UserMapper userMapper;
@Autowired
public CompletableFutureTransactionalService(ThreadPoolExecutor myThreadPool, DataSourceTransactionManager dataSourceTransactionManager, UserMapper userMapper) {
this.myThreadPool = myThreadPool;
this.dataSourceTransactionManager = dataSourceTransactionManager;
this.userMapper = userMapper;
}
/**
* 根据id修改User, 测试CompletableFuture事务问题
* @param userId User主键值
*/
public void updateUser(Integer userId) throws ExecutionException, InterruptedException {
/*
创建CompletableFuture线程
*/
final CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// 事物隔离级别,开启新事务,这样会比较安全些。
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
// 获得事务状态
TransactionStatus status = dataSourceTransactionManager.getTransaction(def);
try {
// 更新用户名字
User user = userMapper.selectById(userId);
user.setName("黄子豪");
userMapper.updateById(user);
// 再次更新用户邮箱
user.setEmail("1111111111@qq.com");
userMapper.updateById(user);
//提交事务
dataSourceTransactionManager.commit(status);
} catch (Exception ex) {
// 如果失败返回异常信息
dataSourceTransactionManager.rollback(status);
}
}, myThreadPool);//自定义线程池
}
}
多线程批量插入事务控制
@Slf4j
public class ThreadTransaction {
@Autowired
private TransactionUtils transactionUtils;
@Autowired
private ThreadPoolExecutor myThreadPool;
@Autowired
private UserMapper userMapper;
public void printList(List<User> list) {
if (list == null || list.isEmpty()){
return;
}
int nThreads = 20;
CyclicBarrier cyclicBarrier = new CyclicBarrier(nThreads);
AtomicReference<Boolean> rollback = new AtomicReference<>(false);
int size = list.size();
for (int i = 0; i < nThreads; i++) {
int start = nThreads * i;
int end = nThreads * (i + 1) > size ? size + 1:nThreads * (i + 1);
final List<User> subList = list.subList(start,end);
myThreadPool.execute(()->{
TransactionStatus transaction = transactionUtils.begin();
try {
//insert操作,返回值小于1,抛出异常
if (userMapper.insertBatch(subList) < 1){
log.info("手动异常");
throw new RuntimeException("插入数据失败");
}
}catch (Exception e){
//如果当前线程异常 则设置回滚标志
rollback.set(true);
log.error("插入数据失败");
}
//等待所有线程的事务结果
try {
cyclicBarrier.await();
} catch (BrokenBarrierException | InterruptedException e) {
throw new RuntimeException(e);
}
if (rollback.get()){
transactionUtils.rollback(transaction);
log.info("rollback");
return;
}
transactionUtils.commit(transaction);
});
}
}
}