Java教程

注解线程池开启异步线程

本文主要是介绍注解线程池开启异步线程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

线程池配置

package com.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author zhujianming
 * @date 2021-04-24 16:37
 */
@Configuration
@EnableAsync  // 启用异步任务
public class ThreadConfig {

    // 执行需要依赖线程池,这里就来配置一个线程池
    @Bean
    public Executor getExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(25);
        executor.initialize();
        return executor;
    }
}

编写异步线程

package com.demo;

import java.util.Random;
import java.util.UUID;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsynTaskService {

    @Async    // 这里进行标注为异步任务,在执行此方法的时候,会单独开启线程来执行
    public void f1() {
        System.out.println("f1 : " + Thread.currentThread().getName() + "   " + UUID.randomUUID().toString());
        try {
            Thread.sleep(new Random().nextInt(100));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async
    public void f2() {
        System.out.println("f2 : " + Thread.currentThread().getName() + "   " + UUID.randomUUID().toString());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}  

调用异步线程

package com.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

/**
 * @author zhujianming
 * @date 2021-04-16 09:26
 */
@Controller
@RequestMapping(value="/user")
public class XXController {

    private @Autowired
    RedisCacheManager redisCacheManager;

    private @Autowired
    AsynTaskService service;

    @RequestMapping(value = "/index2")
    @ResponseBody
    public void async(){
        for (int i = 0; i < 10; i++) {
            service.f1(); // 执行异步任务
            service.f2(); // 执行异步任务
        }
    }

    @RequestMapping(value = "/index")
    @Cacheable(cacheNames = "studentCache", key = "#id")
    @ResponseBody
    public List<User> demo(Model model, @RequestParam(value = "id",defaultValue = "1") Integer id){
        System.out.println("fsfsfa");
        return Arrays.asList(new User(id,"fsfsafa"));
    }
    @GetMapping("/get/cache")
    @ResponseBody
    public String getCache(){
        Cache demoCache = redisCacheManager.getCache("studentCache");
        System.out.println(demoCache.getName());
        System.out.println(demoCache.get(1, List.class));
        return demoCache.getName();
    }

    @RequestMapping(value = "/index1")
    @CachePut(cacheNames = "studentCache", key = "#id")
    @ResponseBody
    public User demo1(Model model,@RequestParam(value = "id",defaultValue = "1") Integer id){
        System.out.println("fsfsfa");
        return new User(id,"tttt");
    }

}

测试

访问 http://localhost:8080/user/index2

发现启动了不同线程,说明成功了

 

这篇关于注解线程池开启异步线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!