java.util.并发: calculating primes

标签 java multithreading primes concurrency

我是新用户 java.util.concurrent 。我创建了以下程序,使用多线程和单线程策略测试一个数字是否为素数。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class IsPrime
        implements Runnable
    {
    private static final long UPPER_BOUND=100000;
    long value;//the number observed
    private IsPrime(long value)
        {
        this.value=value;
        }
    /** returns wether value is a prime number (simple and stupid method ) */
    private boolean isAPrimeNumber()
        {
        if(value==1 || value==2) return true;
        if(value%2L==0) return false;
        for(long i=3;i< value;++i)
            {
            if(this.value%i==0) return false;
            }
        return true;
        }

    @Override
    /** calls isAPrimeNumber */
    public void run()
        {
        boolean result=isAPrimeNumber();
        //if(result) System.out.println("["+this.value+"]");
        }

    /** loop from 3 to UPPER_BOUND, multithreaded */
    private static long loopMT() 
        {
        long now=System.currentTimeMillis();
        ExecutorService service=Executors.newFixedThreadPool(10); 

        for(long i=3;i< UPPER_BOUND;i+=2)
            {
            service.submit(new IsPrime(i));
            }
        service.shutdown();
        return System.currentTimeMillis()-now;
        }

    /** loop from 3 to UPPER_BOUND, NOT multithreaded */
    private static long loop() 
        {
        long now=System.currentTimeMillis();
        for(long i=3;i< UPPER_BOUND;i+=2)
            {
            new IsPrime(i).run();
            }
        return System.currentTimeMillis()-now;
        }

    public static void main(String[] args)
        {
        long n1=IsPrime.loop();
        long n2=IsPrime.loopMT();
        System.out.println(""+n1+" >>> "+n2);   
        }
    }

对于方法loopMT,使用包java.util.concurrent中的类的正确方法是吗?还有另一种(更安全、更优雅)的方式来编写这个程序吗?我可以在多线程环境中使用 System.out 吗?

非常感谢您的建议

皮埃尔

最佳答案

System.outPrintStream 的一个实例它是线程安全的。所以它非常适合训练示例。但通常从不同线程输出对我来说似乎不是一个好主意。最好有专用的输出线程来异步接受输出请求。

也许,我宁愿实现 Callable<Boolean>正如 finnw 所建议的,否则我在 IsPrime 中看不到任何原因。除了CPU消耗之外的类。

关于java.util.并发: calculating primes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2153439/

相关文章:

c# - 非静态方法需要 objective-c #

java - 无法 Autowiring Spring Security 实现类

java - 将字符串映射到枚举 jooq

android - 解释多核性能跟踪 (Eclipse/Android)

CC3200 RTOS 多线程

arrays - 查找素数范围内出现次数最多的数字

Java 使用 const 或 static 方法定义通用类参数

java - 有人可以帮我从数据库中收取 SelectOneMenu 费用吗?

c - 在 C 中搜索素数时遇到问题

C - 当使用 if(input=prime) 限制时,next_prime 函数有时会失败