我正在尝试使用线程来计算非常大数的阶乘但是无线函数的计算速度更快。我如何使用线程并行计算------------------ -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -----------------------------------------------
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();
}
}
答案 0 :(得分:1)
我可以指出有两件事会损害您的线程版本的性能:
如果这对你来说是中文,我建议阅读上下文切换:)