gpt4 book ai didi

Java 使用线程(并发)从文件进行复杂计算

转载 作者:行者123 更新时间:2023-12-02 01:13:59 25 4
gpt4 key购买 nike

所以我有文本文件,我可以用我拥有的代码解析它们并计算空间中的一些原子。问题是我必须使用线程使程序并行,并且我不知道应该如何在每个线程中传递文本文件。

如果我尝试执行类似 double kx = console.nextDouble(); 的操作,它无法识别控制台是什么,因为它的 Scanner 对象位于 内部main() 。我缺少什么?

(注意:直接使用线程并不是绝对必要的;我可以使用 fork-join 池等)

    public class NBodyBH {

//Set value to simulate <execTime> seconds of the bodies
static final int execTime = 100;

static final boolean draw = false;

public static void main(String[] args) throws FileNotFoundException {
String fname = args[0];
FileInputStream is = new FileInputStream(new File(fname));
System.setIn(is);

Scanner console = new Scanner(System.in);

final double dt = 0.1; // time quantum
int N = console.nextInt(); // number of particles
double radius = console.nextDouble(); // radius of universe

//BELOW HERE IS THE PART I WANT TO MAKE PARALLEL
Body[] bodies = new Body[N]; // array of N bodies
for (int i = 0; i < N; i++) {
double px = console.nextDouble();
double py = console.nextDouble();
double vx = console.nextDouble();
double vy = console.nextDouble();
double mass = console.nextDouble();
int red = console.nextInt();
int green = console.nextInt();
int blue = console.nextInt();
Color color = new Color(red, green, blue);
bodies[i] = new Body(px, py, vx, vy, mass, color);
}
}
}

最佳答案

我相信您正在寻找的是 AsynchronousFileChannel 。它是在 Java 7 中引入的,用于文件的异步操作。

虽然,您说您将运行复杂的计算,所以时间密集型任务可能是计算本身而不是文件读取,您可以在主线程中读取文件并使用并行性来运行复杂的计算。

List<Integer> calculationResults = bodies.parallelStream()
.map(doComplexCalculation)
.collect(toList())

在示例中,我假设计算返回一个Integer,并且bodies是一个Collection,就像List code>,但根据您认为合适的情况进行调整。

关于Java 使用线程(并发)从文件进行复杂计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58938867/

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