**
以售票为案例
**
1.创建配置类
package com.cc.myall.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class SpringAsync {
@Bean
public TaskExecutor taskExecutor(){
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//设置核心线程数
executor.setCorePoolSize(5);
//设置最大线程数
executor.setMaxPoolSize(10);
//设置队列容量
executor.setQueueCapacity(20);
//设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
//设置线程名称
executor.setThreadNamePrefix("Thred-");
//设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//等待所有线程任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
2.创建demo
使用循环CAS实现原子操作
package com.cc.myall.component;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
@Component
@Slf4j
public class Hello {
AtomicInteger count = new AtomicInteger(30);
@Async
public Future<Boolean> sayHello() throws Exception {
final ReentrantLock lock = new ReentrantLock();
lock.lock();
int temp = 0;
for (; ; ) {
Thread.sleep(2000);
int j = count.get();
temp = j;
if (temp == 0) {
log.info("票已卖光");
break;
}
final boolean b = count.compareAndSet(j, --j);
if (b) {
log.info("{}:卖出第{}张票,还剩{}张票", Thread.currentThread().getName(), ++j, temp = --temp);
}
}
lock.unlock();
return new AsyncResult<>(true);
}
}
3.创建测试类
@Autowired
Hello hello;
@Test
public void hello() throws Exception {
final ArrayList<Future<Boolean>> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
//阻塞调用返回值
final Future<Boolean> hel = hello.sayHello();
list.add(hel);
if (list.size() == 5) {
while (true) {
for (int j = list.size() - 1; j >= 0; j--) {
final Future<Boolean> aBoolean = list.get(j);
if (aBoolean.isDone()) {
list.remove(j);
}
}
if (list.size() == 0) {
break;
}
}
}
}
}
4.效果展示