日期:2014-05-19  浏览次数:20632 次

JAVA 线程池并发性能问题(代码问题?)
Java code

public class CommentsThreadUtil {
    @Autowired
    private GetFeedCommentsService getFeedCommentsService;
    private static final Log LOGGER = LogFactory
            .getLog(CommentsThreadUtil.class);
    
    private static final int THREADNUM = Runtime.getRuntime()
            .availableProcessors() * 10;
    private static final long TIMEOUT = 100;

    ExecutorService threadPool = Executors.newFixedThreadPool(THREADNUM);

    @Profiled
    public void excute(int host, List<MatterFeedData> matterFeedDatas,
            ProcessMatterCommentBuilder processMatterCommentBuilder) {
        for (MatterFeedData matterFeedData : matterFeedDatas) {
            threadPool.execute(new SimpleThread(host, matterFeedData,
                    processMatterCommentBuilder));
        }
        try {
            if (!threadPool.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS)) {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("timeout:" + host
                            + ",matterFeedData=" + matterFeedDatas);
                }
            }
        } catch (InterruptedException e) {
            // threadPool.shutdownNow();
            LOGGER.error("取评论线程池执行出错:host=" + host, e);
        }
    }

    class SimpleThread implements Runnable {
        private int host;
        private MatterFeedData matterFeedData;
        private ProcessMatterCommentBuilder processMatterCommentBuilder;

        public SimpleThread(int host, MatterFeedData matterFeedData,
                ProcessMatterCommentBuilder processMatterCommentBuilder) {
            this.host = host;
            this.matterFeedData = matterFeedData;
            this.processMatterCommentBuilder = processMatterCommentBuilder;
        }

        @Override
        public void run() {
            List<MatterComment> matterComments = getFeedCommentsService
                    .getFeedComments(host, matterFeedData.getUgcInfo(),
                            processMatterCommentBuilder);
            matterFeedData.setMatterComments(matterComments);
        }
    }
}




如上代码,下面每个线程执行时间10ms,但是为什么线程池中每次execute执行是102左右ms,每次调用execute方法,参数list大小为10,即每次并发10个线程。

为什么用了线程池,时间和串行10个线程没区别?

------解决方案--------------------
不知道你的run中是什么类型的任务,是IO密集型还是计算密集型

以及IO与计算的比例

如果是纯计算密集型,线程数超过CPU数就可能降低性能了

最佳线程数大概可以这么算 = CPU(核)数/(1-阻塞率)

阻塞率是需要观察计算得到的