美文网首页
线程池工具类以及Future使用

线程池工具类以及Future使用

作者: c_gentle | 来源:发表于2022-08-23 16:47 被阅读0次
    1、线程池工具

    采用单利模式以及double check + volitile,保证线程安全,然后交给spring管理

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.util.concurrent.*;
    @Configuration
    public class ExecutorServiceUtil {
        private static volatile ExecutorService executorService =null;
        private static Object object = new Object();
        private ExecutorServiceUtil(){
        }
        @Bean(name="executorService")
        public  ExecutorService getExecutorService() {
            if (executorService==null){
                synchronized (object){
                    if (executorService==null){
                        String queueSize = "100";
                        String threadSize = "10";
                        if (executorService != null) {
                            return executorService;
                        }
                        int poolSize = Integer.parseInt(queueSize);
                        int coreSize = Integer.parseInt(threadSize);
                        if (poolSize < coreSize) {
                            coreSize = poolSize;
                        }
                        ThreadFactory tf = Executors.defaultThreadFactory();
                        BlockingQueue<Runnable> queueToUse = new LinkedBlockingQueue<Runnable>(poolSize);
                        final ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, poolSize, 60,
                                TimeUnit.SECONDS, queueToUse, tf, new ThreadPoolExecutor.CallerRunsPolicy());
                        executorService=executor;
                    }
                }
            }
            return executorService;
        }
    }
    
    2、Future使用
    import org.springframework.util.StringUtils;
    
    import javax.annotation.Resource;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.concurrent.Callable;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Future;
    
    public class ThreadDemo {
        @Resource
        private ExecutorService executorService;
    
        public void test() throws Exception {
            ExecutorService executorService1 = this.executorService;
            CountDownLatch countDownLatch = new CountDownLatch(4);
            String[] tempTypes = new String[]{"LOL", "DNF", "CF", "OTHER"};
            Map<String, Future<String>> createMap = new HashMap<String, Future<String>>();
            for (String tempType : tempTypes) {
                Future<String> craeteFlag = executorService1.submit(new CreateAcctFileThread(tempType, countDownLatch));
                createMap.put(tempType, craeteFlag);
            }
            Iterator<Map.Entry<String, Future<String>>> iterator = createMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Future<String>> entry = iterator.next();
                if (("SUCCESS").equals(entry.getValue().get())) {
                    continue;
                } else {
                    String errorMsg = entry.getValue().get();
                    if (!StringUtils.isEmpty(errorMsg) && errorMsg.length() > 300) {
                        errorMsg = errorMsg.substring(0, 300);
                    }
                    throw new Exception("去打" + entry.getKey() + "时发生异常,异常信息" + errorMsg);
                }
            }
            countDownLatch.await();
        }
    
        static class CreateAcctFileThread implements Callable<String> {
            private String tempType;
            private CountDownLatch countDownLatch;
    
            CreateAcctFileThread(String tempType, CountDownLatch countDownLatch) {
                this.tempType = tempType;
                this.countDownLatch = countDownLatch;
    
            }
    
            public String getTempType() {
                return tempType;
            }
    
            public void setTempType(String tempType) {
                this.tempType = tempType;
            }
    
            @Override
            public String toString() {
                return "CreateAcctFileThread{" +
                        "tempType='" + tempType + '\'' +
                        '}';
            }
    
            public String call() {
                try {
                    if ("LOL".equals(tempType)) {
                        System.out.println("去打LOL");
                    } else if ("DNF".equals(tempType)) {
                        System.out.println("去打DNF");
                    } else if ("CF".equals(tempType)) {
                        System.out.println("去打CF");
                    } else {
                        System.out.println("去玩别的游戏");
                    }
                } catch (Throwable e) {
                    return e.getMessage();
                } finally {
                    System.out.println(tempType + "进行countDown操作");
                    countDownLatch.countDown();
                }
                return "SUCCESS";
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:线程池工具类以及Future使用

          本文链接:https://www.haomeiwen.com/subject/ulsggrtx.html