SpringBoot实现多线程共享变量

**

以售票为案例

**
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.效果展示
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值