線程等待

自己看的,亂寫的,勿噴

線程配置類

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<Integer> submit1 = executor.submit(callable);
            Future<Integer> submit2 = executor.submit(callable);
            Future<Integer> 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;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容