zoukankan      html  css  js  c++  java
  • 线程解决并发问题

    public final class MyThreadPool {

        /**
         * 线程池大小设置,系统设计等待时间最长为3000ms,单次查询数据库大约消耗600ms
         * <P>
         * 故而FACTOR设置为6 FACTOR = (1+WT/ST);
         */
        private static final int FACTOR = 6;

        /**
         * 线程池大小设置,N为CPU核心数
         * <P>
         * N = N * FACTOR
         */
        private static final ExecutorService executorService = Executors
                .newFixedThreadPool(Runtime.getRuntime().availableProcessors()
                        * FACTOR);
        
        private MyThreadPool() {

        }

        /**
         * 执行线程
         *
         * @param command
         */
        public static void execute(Runnable command) {
            executorService.execute(command);
        }

        @SuppressWarnings("rawtypes")
        public static Future submit(Runnable task) {
            return executorService.submit(task);
        }
    }

    在定义一个类继承Thread,实现run方法,在该方法中写相关逻辑;

    new一个该自定义的类,名称自定义,放在submit中,如下。

    Future future = MyThreadPool.submit(qdt);

    然后

    /**
         *  等待各个线程任务完成
         * @param futures
         */

    private void waitForThreads(List<Future> futures) {
            if (futures != null) {
                for (Future future : futures) {
                    try {
                        future.get();
                    } catch (InterruptedException | ExecutionException e) {
                      
                        e.printStackTrace();
                    }
                }
            }
        }

    即可。

  • 相关阅读:
    Seaborn相关
    Matplot相关(二)——统计图
    PAT 甲级真题
    数学题一
    Codeforces Round #467 (Div. 2)
    国庆 Day1
    [NOIP 2005] 运输计划
    dp专题练习
    YBT 2.4 AC自动机
    [模板]树链剖分
  • 原文地址:https://www.cnblogs.com/yanduanduan/p/4990783.html
Copyright © 2011-2022 走看看