gpt4 book ai didi

java - 如何让这个程序在Java中最后显示正确的值?

转载 作者:行者123 更新时间:2023-12-01 17:29:04 25 4
gpt4 key购买 nike

我在函数末尾获取正确的值时遇到问题。我不明白如何让主线程等待执行程序完成,这样我就可以显示正确的值。

每个任务计算数组中索引 i 处的值的乘积。我将产品变量设置为 volatile ,并同步计算产品的函数,以确保只有一个线程可以访问它并修改它。但我无法安排线程等待执行程序完成然后显示答案。

 public class NewBetterDot {
static double[] vectorOne;
static double[] vectorTwo;
private static volatile double product;;

public NewBetterDot(double[] vectorOne, double[] vectorTwo, double product) {
super();
this.vectorOne = vectorOne;
this.vectorTwo = vectorTwo;
this.product = product;

}

public static synchronized double smallDot(int i) {

double multi = vectorOne[i] * vectorTwo[i];
return multi;
}

static class Task implements Runnable {
int i;

@Override
public void run() {

// System.out.println("Before operation: " + product);

product = product + NewBetterDot.smallDot(i);

System.out.println(Thread.currentThread().getName() + " Product is equal to: " + product);

}

public Task(int i) {
super();
this.i = i;
}

}

static class PrintTask implements Runnable {
@Override
public void run() {
System.out.println("Product equals to: " + product);
}
}

public static void main(String[] args) throws NullPointerException {

double sum = 0.0;
NewBetterDot objectOne = new NewBetterDot(new double[] { 5.0, 4.0, 1.0 }, new double[] { 1.0, 2.0, 3.0 }, 0.0);

int threshhold = vectorOne.length;

ExecutorService executor = Executors.newFixedThreadPool(2);
;

for (int i = 0; i < threshhold; i++) {

NewBetterDot.Task task = new NewBetterDot.Task(i);

executor.submit(task);

}

executor.shutdown();

NewBetterDot.PrintTask pt = new NewBetterDot.PrintTask();
pt.run();
}

}

Blockquote

最佳答案

shutdown() 的文档说:

This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

此代码最多等待 1 分钟才能停止计算:

executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);

关于java - 如何让这个程序在Java中最后显示正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61159786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com