【问题标题】:Java factorial calculation with thread pool使用线程池进行 Java 阶乘计算
【发布时间】:2017-04-28 05:51:00
【问题描述】:

我实现了在没有池的情况下使用两个线程计算阶乘。我有两个阶乘类,分别命名为 Factorial1、Factorial2 并扩展了 Thread 类。让我们考虑一下我想计算!160000 的值。在 Factorial1 的 run() 方法中,我在 for 循环中从 i=2 到 i=80000 以及在 Factorial2 中从 i=80001 到 160000 进行乘法。之后,我返回两个值并在 main 方法中将它们相乘。当我比较执行时间时(即 5000 毫秒)比非线程计算的时间(15000 毫秒)要好得多,即使有两个线程也是如此。

现在我想写干净更好的代码,因为我在阶乘计算中看到了线程的效率,但是当我使用线程池计算阶乘值时,并行计算总是比非线程计算花费更多时间(几乎16000)。我的代码片段如下所示:

for(int i=2; i<= Calculate; i++)
{
    myPool.execute(new Multiplication(result, i));
}

在乘法类中的run()方法:

public void run() 
{
        s1.Mltply(s2); // s1 and s2 are instances of my Number class
                       // their fields holds BigInteger values
}

Number 类中的 Mltply() 方法:

public void Multiply(int number)
{
    area.lock(); // result is going wrong without lock
    Number temp = new Number(number);
    value = value.multiply(temp.value); // value is a BigInteger
    area.unlock();       
}

在我看来,这个锁可能会扼杀线程使用的所有优势,因为看起来线程所做的只是乘法,而没有别的。但没有它,我什至无法计算出真正的结果。假设我要计算 !10,所以 thread1 计算 10*9*8*7*6,thread2 计算 5*4*3*2*1。这就是我要找的方式吗?甚至可以使用线程池吗?当然执行时间必须小于正常计算...

感谢您的所有帮助和建议。

编辑:-我自己解决问题的方法-

public class MyMultiplication implements Runnable 
{
    public static BigInteger subResult1;
    public static BigInteger subResult2;
    int thread1StopsAt;
    int thread2StopsAt;
    long threadId;
    static boolean idIsSet=false;

    public MyMultiplication(BigInteger n1, int n2)  // First Thread
    {
        MyMultiplication.subResult1 = n1;
        this.thread1StopsAt = n2/2;

        thread2StopsAt = n2;

    }
    public MyMultiplication(int n2,BigInteger n1)   // Second Thread
    {
        MyMultiplication.subResult2 = n1;
        this.thread2StopsAt = n2;

        thread1StopsAt = n2/2;
    }
    @Override
    public void run() 
    {
        if(idIsSet==false)
        {
            threadId = Thread.currentThread().getId(); 
            idIsSet=true;            
        }
        if(Thread.currentThread().getId() == threadId)
        {
            for(int i=2; i<=thread1StopsAt; i++)
            {
                subResult1 = subResult1.multiply(BigInteger.valueOf(i));
            }
        }
        else
        {
            for(int i=thread1StopsAt+1; i<= thread2StopsAt; i++)
            {
                subResult2 = subResult2.multiply(BigInteger.valueOf(i));
            }
        }            
    }   
}
public class JavaApplication3 
{
    public static void main(String[] args) throws InterruptedException 
    {
        int calculate=160000;
        long start = System.nanoTime(); 
        BigInteger num = BigInteger.valueOf(1);
        for (int i = 2; i <= calculate; i++) 
        {
          num = num.multiply(BigInteger.valueOf(i));
        }
        long end = System.nanoTime();
        double time = (end-start)/1000000.0;
        System.out.println("Without threads: \t" + 
        String.format("%.2f",time) + " miliseconds");    
        System.out.println("without threads Result: " + num);

        BigInteger num1 = BigInteger.valueOf(1);
        BigInteger num2 = BigInteger.valueOf(1);
        ExecutorService myPool = Executors.newFixedThreadPool(2);
        start = System.nanoTime();

            myPool.execute(new MyMultiplication(num1,calculate));  
            Thread.sleep(100);
            myPool.execute(new MyMultiplication(calculate,num2));

        myPool.shutdown();
        while(!myPool.isTerminated())   {}  // waiting threads to end
        end = System.nanoTime();
        time = (end-start)/1000000.0;
        System.out.println("With threads: \t" +String.format("%.2f",time) 
        + " miliseconds");    
        BigInteger result = 

        MyMultiplication.subResult1.
        multiply(MyMultiplication.subResult2);
        System.out.println("With threads Result: " + result);
        System.out.println(MyMultiplication.subResult1);
        System.out.println(MyMultiplication.subResult2);
    }   
}

输入:!160000 无线程执行时间:15000 毫秒 2个线程的执行时间:4500毫秒

感谢您的想法和建议。

【问题讨论】:

  • 你遗漏了太多细节:minimal reproducible example
  • 这条线是做什么的:Number temp = new Number(number); 我看不到 temp 正在使用。
  • 除非您计算一个非常大的数字的阶乘,例如 10,000,否则您不会看到多线程带来的一致改进。线程管理的开销将压倒拆分计算的任何优势,并且由于 JIT 预热时间,您无法对 10,000 次迭代计数进行微基准测试。简而言之,对于这样一个小问题,您不需要也不想要多线程。
  • @Jhonny007 我在 multiply() 函数中使用 temp
  • @JimGarrison 我在上面提到过,我在没有线程(15000 毫秒)和两个线程(5000 毫秒)的情况下计算了 !160000。所以我认为 160000 比 10000 大得多,对于这么小的过程来说,10 秒并不是一个“小”的时间。我想知道如何使用线程池实现相同的目标,无论如何,谢谢。

标签: java multithreading threadpool factorial


【解决方案1】:

您可以在不使用锁的情况下同时计算 !160000,方法是将 160000 拆分为不连贯的垃圾,正如您通过将其拆分为 2..80000 和 80001..160000 所解释的那样。

但您可以通过使用 Java Stream API 来实现:

IntStream.rangeClosed(1, 160000).parallel()
    .mapToObj(val -> BigInteger.valueOf(val))
    .reduce(BigInteger.ONE, BigInteger::multiply);

它完全符合您的要求。它将整个范围分成垃圾,建立一个线程池并计算部分结果。然后它将部分结果合并为一个结果。

那你为什么要费心自己做呢?只是练习干净的编码?

在我真正的 4 核机器上,for 循环中的计算时间是使用并行流的 8 倍。

【讨论】:

  • 我只是想知道我是否可以使用线程池获得相同的结果和良好的执行时间。我是线程池的新手,但我想这可以用它来完成,只是不知道该怎么做。我认为仅在 run() 方法中使用不同的 for 循环创建两个相同的阶乘类并不是清晰的代码。
【解决方案2】:

线程必须独立运行才能快速运行。许多依赖项,例如锁、代码的同步部分或某些系统调用,会导致等待访问某些资源的线程处于休眠状态。

在您的情况下,您应该尽量减少线程在锁内的时间。也许我错了,但似乎您为每个数字创建了一个线程。所以对于1.000!,你产生了 1.000 个线程。他们都试图获得area 上的锁并且无法计算任何东西,因为一个线程已成为锁,而所有其他线程都必须等到锁再次解锁。因此,线程仅以串行方式运行,与您的非线程示例一样快,加上锁定和解锁、线程管理等的额外时间。哦,由于 cpu 的上下文切换,它变得更糟了。

您第一次尝试将阶乘拆分为两个线程会更好。每个线程都可以计算自己的结果,只有当它们完成后,线程才必须相互通信。所以他们大部分时间都是独立的。

现在您必须概括此解决方案。为了减少 cpu 的上下文切换,您只需要与 cpu 的内核一样多的线程(可能因为您的操作系统而少一点)。每个线程都会得到一系列数字并计算它们的乘积。在此之后,它会锁定整体结果并将自己的结果添加到其中。

这应该会改善您的问题的性能。


更新:您寻求更多建议:

您说您有两个课程Factorial1 和Factorial2。可能他们有自己的范围硬代码。您只需要一个将范围作为构造函数参数的类。这个类实现了 Runnable,所以它有一个 run-Method ,该方法将该范围内的所有值相乘。

在你main-方法中你可以做这样的事情:

int n = 160_000;
int threads = 2;
ExecutorService executor = Executors.newFixedThreadPool(threads);
for (int i = 0; i < threads; i++) {
    int start = i * (n/threads) + 1;
    int end = (i + 1) * (n/threads) + 1;
    executor.execute(new Factorial(start, end));
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.DAYS);

现在您已经计算了每个线程的结果,但没有计算整体结果。这可以通过BigInteger 对Factorial 类可见(就像同一主类中的static BigInteger reuslt;)和锁来解决。在Factorial的run-方法中可以通过加锁来计算整体结果,计算结果:

Main.lock.lock();
Main.result = Main.result.multiply(value);
Main.lock.unlock();

对未来的一些额外建议:这不是很干净,因为Factorial 需要有关您的主类的信息,因此它依赖于它。但是ExecutorService返回一个Future&lt;T&gt;-Object,可以用来接收线程的结果。使用这个Future-Object 你不需要使用锁。但这需要一些额外的工作,所以现在试着让它运行;-)

【讨论】:

  • 感谢您的建议。但是您对我如何在线程池中模仿我的第一个成功方法有什么建议吗?
【解决方案3】:

除了我的 Java Stream API 解决方案之外,还有另一个解决方案,它根据您的要求使用自管理线程池:

public static final int CHUNK_SIZE = 10000;

public static BigInteger fac(int max) {
    ExecutorService executor = newCachedThreadPool();
    try {
        return rangeClosed(0, (max - 1) / CHUNK_SIZE)
                .mapToObj(val -> executor.submit(() -> prod(leftBound(val), rightBound(val, max))))
                .map(future -> valueOf(future))
                .reduce(BigInteger.ONE, BigInteger::multiply);
    } finally {
        executor.shutdown();
    }
}

private static int leftBound(int chunkNo) {
    return chunkNo * CHUNK_SIZE + 1;
}

private static int rightBound(int chunkNo, int max) {
    return Math.min((chunkNo + 1) * CHUNK_SIZE, max);
}

private static BigInteger valueOf(Future<BigInteger> future) {
    try {
        return future.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private static BigInteger prod(int min, int max) {
    BigInteger res = BigInteger.valueOf(min);
    for (int val = min + 1; val <= max; val++) {
        res = res.multiply(BigInteger.valueOf(val));
    }
    return res;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多