手机版
你好,游客 登录 注册
背景:
阅读新闻

Java 下计算质数的多线程跟单线程执行代码分析

[日期:2012-11-21] 来源:Linux社区  作者:zhongweijian [字体:大 中 小]

在我的Ubutun下双核cpu的输出

单线程下的执行结果

Number of primes under 10000000 is 664579 
Time (seconds) taken is 7.518444261 

多线程下

package com.mime; 
 
import Java.util.ArrayList; 
import java.util.List; 
import java.util.concurrent.Callable; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.Future; 
import java.util.concurrent.TimeUnit; 
 
public class ConcurrentPrimeFinder extends AbstractPrimeFinder { 
    private final int poolSize; 
    private final int numberOfParts; 
 
    public ConcurrentPrimeFinder(final int thePoolSize, 
            final int theNumberOfParts) { 
        poolSize = thePoolSize; 
        numberOfParts = theNumberOfParts; 
    } 
 
    public int countPrimes(final int number) { 
        int count = 0; 
        try { 
            final List<Callable<Integer>> partitions = new ArrayList<Callable<Integer>>(); 
            final int chunksPerPartition = number / numberOfParts; 
            for (int i = 0; i < numberOfParts; i++) { 
                final int lower = (i * chunksPerPartition) + 1; 
                final int upper = (i == numberOfParts - 1) ? number : lower 
                        + chunksPerPartition - 1; 
                partitions.add(new Callable<Integer>() { 
                    public Integer call() { 
                        return countPrimesInRange(lower, upper); 
                    } 
                }); 
            } 
            final ExecutorService executorPool = Executors 
                    .newFixedThreadPool(poolSize); 
            final List<Future<Integer>> resultFromParts = executorPool 
                    .invokeAll(partitions, 10000, TimeUnit.SECONDS); 
            executorPool.shutdown(); 
            for (final Future<Integer> result : resultFromParts) 
                count += result.get(); 
        } catch (Exception ex) { 
            throw new RuntimeException(ex); 
        } 
        return count; 
    } 
 
    public static void main(final String[] args) { 
            new ConcurrentPrimeFinder(4,100).timeAndCompute(10000000); 
    } 
 
} 

输出

Number of primes under 10000000 is 664579 
Time (seconds) taken is 3.825282456 

可以根据cpu个数和调整分区树来调优这个线程数来达到最有效果。 

linux
相关资讯       Java教程  Java多线程代码  Java单线程  Java求质 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款