线程等待

自己看的,乱写的,勿喷

线程配置类

package mau5.top.myproject.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadAsyncConfigurer implements AsyncConfigurer {

    private final static Logger log = LoggerFactory.getLogger(ThreadAsyncConfigurer.class);

    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        threadPool.setCorePoolSize(3);
        // 设置最大线程数
        threadPool.setMaxPoolSize(8);
        // 线程池所使用的缓冲队列
        threadPool.setQueueCapacity(10);
        // 等待任务在关机时完成--表明等待所有线程执行完
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(60);
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程
        threadPool.initialize();
        return threadPool;
    }

    /**
     * 异常处理
     *
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }

    /**
     * 自定义异常处理类
     */
    class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
            log.error("==========================" + throwable.getMessage() + "=======================", throwable);
            log.error("exception method:" + method.getName());
            for (Object param : obj) {
                log.error("Parameter value - " + param);
            }
        }
    }
}

写一个Callable实现类实现业务

package mau5.top.myproject.business.callable;

import java.util.concurrent.*;

public class TestCallable implements Callable {
    @Override
    public Object call() throws Exception {

        int random = (int) (Math.random() * 10000);
        System.out.println("随机生成数:" + random);
        Thread.sleep(random);
        return random;
    }    
}

调用Callable实现类

package mau5.top.myproject.business.controller;

import mau5.top.myproject.business.callable.TestCallable;
import mau5.top.myproject.business.entity.po.CommodityCategory;
import mau5.top.myproject.business.service.ICommodityCategoryService;
import mau5.top.myproject.common.config.ThreadAsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/cate")
public class CommodityCategoryController {

    @Resource
    private ThreadAsyncConfigurer threadAsyncConfigurer;

    @GetMapping("/testCallable")
    public Object callable(){
        try {
            long currentTimeMillis = System.currentTimeMillis();
            TestCallable callable = new TestCallable();

            // 手动创建线程
            // ExecutorService executor = Executors.newFixedThreadPool(3);
            // 使用线程池
            ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor)threadAsyncConfigurer.getAsyncExecutor();

            Future submit1 = executor.submit(callable);
            Future submit2 = executor.submit(callable);
            Future submit3 = executor.submit(callable);

            int s = submit1.get() + submit2.get() +submit3.get();

            long currentTimeMillis2 = System.currentTimeMillis();

            System.out.println("总共时间:" + s);
            System.out.println("耗时:" + (currentTimeMillis2 - currentTimeMillis));
            // 非线程池时才用shutdown
            // executor.shutdown();
            
            return  "总共时间:" + s + ",耗时:" + (currentTimeMillis2 - currentTimeMillis);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

你可能感兴趣的:(线程等待)