使用线程进行Java因子计算

时间:2017-04-27 17:40:41

标签: java multithreading factorial thread-synchronization

我正在尝试使用线程来计算非常大数的阶乘但是无线函数的计算速度更快。我如何使用线程并行计算------------------ -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -----------------------------------------------

public class Faktoriyel implements Runnable{

private Sayi sayi;
public Sayi faktoriyelSonuc;
public Faktoriyel(Sayi sayi){
    this.sayi = sayi;
}

@Override
public void run() {
BigInteger fact = new BigInteger("1");
for (int i = 1 ;i <= sayi.GetSayi().longValue() ; i++) {
    fact = fact.multiply(new BigInteger(i + ""));
    }     
faktoriyelSonuc = new Sayi(fact.toString());
System.out.println(faktoriyelSonuc.GetSayi());
}
}

这些是主要的---

public class Project1{

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    long baslangicSeri = System.nanoTime();
    System.out.println(SeriFaktoriyel(new Sayi("200000")));
    long bitisSeri = System.nanoTime();
    double SerigecenSure = (double)(bitisSeri-baslangicSeri)/1000000000;
    System.out.println("Seri Hesaplama : "+SerigecenSure+" saniye");

    long baslangicParalel = System.nanoTime();
    ExecutorService havuz = Executors.newFixedThreadPool(10);
    havuz.execute(new Faktoriyel(new Sayi("200000")));
    havuz.shutdown();
    while(!havuz.isTerminated()){ }
    long bitisParalel = System.nanoTime();
    double gecenSure = (double)(bitisParalel-baslangicParalel)/1000000000;
    System.out.println("Paralel hesaplama : "+gecenSure+" saniye");     
} 

public static String SeriFaktoriyel(Sayi sayi){
     BigInteger fact = new BigInteger("1");
for (int i = 1; i <= sayi.GetSayi().longValue() ; i++) {
    fact = fact.multiply(new BigInteger(i + ""));
    }
   return fact.toString();
}
}

1 个答案:

答案 0 :(得分:1)

我可以指出有两件事会损害您的线程版本的性能:

  • System.out.println()是一个系统调用,它有很大的开销,只在线程版本中应用。
  • 您正在使用大小为10的线程池,除非您的计算机上有10个内核,这意味着您的程序会受到冗余上下文切换的影响。 (使用实际pc内核数量的线程池,您将获得更好的性能)

如果这对你来说是中文,我建议阅读上下文切换:)