Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
并行化基本java任务_Java_Multithreading - Fatal编程技术网

并行化基本java任务

并行化基本java任务,java,multithreading,Java,Multithreading,我创建了一个简单的顺序java程序,它使用两种不同的方法(math.pow()和Fast inverse square root)计算数字的平方根反比,以比较结果的准确性和完成时间。现在我需要并行化这个任务,这样一个线程使用math.pow计算平方根的倒数,另一个线程使用FISR计算平方根的倒数。我不确定该怎么做,因为我看到的每个多线程示例都有两个线程处理一个问题的两个部分,而不仅仅是运行单独的任务。我的源代码如下: package paralleltask; public class Pa

我创建了一个简单的顺序java程序,它使用两种不同的方法(math.pow()和Fast inverse square root)计算数字的平方根反比,以比较结果的准确性和完成时间。现在我需要并行化这个任务,这样一个线程使用math.pow计算平方根的倒数,另一个线程使用FISR计算平方根的倒数。我不确定该怎么做,因为我看到的每个多线程示例都有两个线程处理一个问题的两个部分,而不仅仅是运行单独的任务。我的源代码如下:

package paralleltask;


public class ParallelTask {

    public static void main(String[] args) {
            System.out.println("Please enter the value:");
            Scanner userInputScanner = new Scanner(System.in);
            int userIn = userInputScanner.nextInt();
            long totalStart = System.nanoTime();
            long powStart = System.nanoTime();
            double testNum = Math.pow(userIn, -1.0/2);
            long powEnd = System.nanoTime();
            long powDuration = powEnd - powStart;
            long FISRStart = System.nanoTime();
            float xhalf = 0.5f*userIn;
            int i = Float.floatToIntBits(userIn);
            i = 0x5f3759df - (i>>1);
            Float x = Float.intBitsToFloat(i);
            x = x*(1.5f - xhalf*x*x);
            long FISREnd = System.nanoTime();
            long totalEnd = System.nanoTime();
            long totalDuration = totalEnd - totalStart;
            long FISRDuration = FISREnd - FISRStart;
            String testNumString = String.valueOf(testNum);
            String FISR = String.valueOf(x);
            System.out.println("The inverse square root using the math.pow() function is:");
            System.out.println(testNumString);
            System.out.println("It took " + powDuration + " milliseconds to complete");
            System.out.println("The inverse square root using the FISR function is:");
            System.out.println(FISR);
            System.out.println("It took " + FISRDuration + " milliseconds to complete");
            if (testNum > x) {
                System.out.println("The FISR approximation was " + (testNum - x) + " smaller than the math.pow() value.");
            }
            if (testNum < x) {
                System.out.println("The FISR approximation was " + (x - testNum) + " larger than the math.pow() value.");
            }
            System.out.println("The FISR function completed " + (powDuration - FISRDuration) + " milliseconds faster than math.pow");
            System.out.println("The total completion time was " + totalDuration + " milliseconds.");
        }
包并行任务;
公共类并行任务{
公共静态void main(字符串[]args){
System.out.println(“请输入值:”);
Scanner userInputScanner=新扫描仪(System.in);
int userIn=userInputScanner.nextInt();
long totalStart=System.nanoTime();
long powStart=System.nanoTime();
double testNum=Math.pow(userIn,-1.0/2);
long powEnd=System.nanoTime();
长功率持续时间=功率结束-功率启动;
long FISRStart=System.nanoTime();
浮动xhalf=0.5f*userIn;
int i=Float.floatToIntBits(userIn);
i=0x5f3759df-(i>>1);
Float x=Float.intBitsToFloat(i);
x=x*(1.5f-xhalf*x*x);
long-FISREnd=System.nanoTime();
long totalEnd=System.nanoTime();
长totalDuration=totalEnd-totalStart;
长FISRDuration=FISREnd-FISRStart;
String testNumString=String.valueOf(testNum);
字符串FISR=字符串的值(x);
System.out.println(“使用math.pow()函数的平方根倒数为:”;
System.out.println(testNumString);
System.out.println(“完成所需的时间为“+powDuration+”毫秒”);
System.out.println(“使用FISR函数的平方根反比为:”);
系统输出打印LN(FISR);
System.out.println(“需要“+FISRDuration+”毫秒才能完成”);
如果(testNum>x){
println(“FISR近似值比math.pow()值小”+(testNum-x)+”;
}
if(testNum

}

我不会称之为并行,而是运行两个并发任务(因为您不需要在多个线程中运行一个计算来加快速度,而是在不同的线程中运行两个单独的计算)。如果要同时运行这两个程序,可以使用
Executor

首先,我将重构代码,将两个计算作为一个单独的任务:

public class MathPowCalculation implements Callable<Double> {
    private final int input;

    public MatPowCalculation(int input) {
        this.input = input;
    }

    @Override
    public Double call() throws Exception {
        // your calculation and time measurement and logging
        return result;
    }
}
公共类MathPowCalculation实现可调用{
私人最终输入;
公共计算(整数输入){
这个输入=输入;
}
@凌驾
public Double call()引发异常{
//您的计算、时间测量和日志记录
返回结果;
}
}
第二种算法也是类似的

然后,您可以同时启动这两个计算,并通过以下方式接收第一个可用结果:

int input = ...;
ExecutorService executor = Executors.newFixedThreadPool(2);
List<Future<Double>> results = executor.invokeAll(Arrays.asList(new MathPowCalculation(input), new FISRCalculation(input)));

for (Future<Double> result : results) {
    Double value = result.get();
    // do something with result value
}

executor.shutdown();
int输入=。。。;
ExecutorService executor=Executors.newFixedThreadPool(2);
列表结果=executor.invokeAll(Arrays.asList(新的MathPowCalculation(输入)),新的FISRCalculation(输入));
用于(未来结果:结果){
Double value=result.get();
//用结果值做某事
}
executor.shutdown();
您还可以看看,它可能会使您的代码更简单


然而,正如其他人在评论中提到的,你不会得到可靠的结果。微基准测试(JVM JIT优化等)是一门完整的科学,如果你想得到有用的结果,你需要为此使用一个框架。

你应该使用一个微基准框架。Paghetti代码不能并行化。首先看基准测试conecpts,然后看@fge建议的内容。同时将其作为两个独立的线程运行可能不是一个好主意。您希望实现什么?为什么并行运行?@isnot2bad我想让程序的整体完成时间更快,所以我想让它多线程运行,而不是串联运行两种计算方法。这不是我出于个人原因而做的事情,这是我需要完成的一项任务,以演示任务的并行性,因此切换到基准测试框架不是重点。我不在乎并行化改变计算时间的速度有多快,我只想看看程序如何并行化。谢谢你的输入,这肯定是朝着正确的方向推进,但我需要输出和它们的完成时间进行比较,仅仅知道哪个先完成是不够的。@broski我根据你的评论更新了我的答案。如果您不仅希望打印调用方法中的时间,而且希望在
未来
中接收它们,那么您需要返回自己的包装类,其中包含结果值和时间信息,而不仅仅是
Double
@broski,并且您必须调用
invokeAll
而不是
invokeAny
,因为您对这两个结果都感兴趣,不仅是第一个完成。