gpt4 book ai didi

java - ForkJoinPool,如何打印出每个工作线程的ID?

转载 作者:行者123 更新时间:2023-11-30 10:48:43 25 4
gpt4 key购买 nike

我是 Java 的新手,正在尝试学习 fork/join 框架。我在网上看到下面的代码,但是,在我运行代码之后,输出似乎是乱序的。所以我只是想知道是否有任何方法可以打印出每个工作线程的 ID?输出非常困惑,没有 ID 来识别哪个线程在做什么。

来源::

public class MyRecursiveTask extends RecursiveTask<Long> {

public static void main(String[] args) {
MyRecursiveTask myRecursiveTask = new MyRecursiveTask(128);
ForkJoinPool fjp1 = new ForkJoinPool();
long mergedResult = fjp1.invoke(myRecursiveTask);



System.out.println("mergedResult = " + mergedResult);
}

private long workLoad = 0;

public MyRecursiveTask(long workLoad) {
this.workLoad = workLoad;
}

protected Long compute() {

//if work is above threshold, break tasks up into smaller tasks
if (this.workLoad > 16) {
System.out.println("Splitting workLoad : " + this.workLoad);

List<MyRecursiveTask> subtasks
= new ArrayList<MyRecursiveTask>();
subtasks.addAll(createSubtasks());

for (MyRecursiveTask subtask : subtasks) {
subtask.fork();
}

long result = 0;
for (MyRecursiveTask subtask : subtasks) {
result += subtask.join();
}
return result;

} else {
System.out.println("Doing workLoad myself: " + this.workLoad);
return workLoad * 3;
}
}

private List<MyRecursiveTask> createSubtasks() {
List<MyRecursiveTask> subtasks
= new ArrayList<MyRecursiveTask>();

MyRecursiveTask subtask1 = new MyRecursiveTask(this.workLoad / 2);
MyRecursiveTask subtask2 = new MyRecursiveTask(this.workLoad / 2);

subtasks.add(subtask1);
subtasks.add(subtask2);

return subtasks;
}
}

输出:

Splitting workLoad : 128
Splitting workLoad : 64
Splitting workLoad : 32
Splitting workLoad : 64
Doing workLoad myself: 16
Splitting workLoad : 32
Doing workLoad myself: 16
Doing workLoad myself: 16
Splitting workLoad : 32
Doing workLoad myself: 16
Doing workLoad myself: 16
Splitting workLoad : 32
Doing workLoad myself: 16
Doing workLoad myself: 16
Doing workLoad myself: 16
mergedResult = 384

最佳答案

compute() 是此任务执行的主要计算。您应该在此处放置用于获取线程 ID 的代码。修改你的 System.out.println 如下:

System.out.println("Splitting workLoad : "+ this.workLoad + "by thread "+ Thread.currentThread().getId());
System.out.println("Splitting workLoad : "+ this.workLoad + "by thread "+ Thread.currentThread().getId());

我的观点是,您应该使用线程名称 (Thread.currentThread().getName()) 而不是线程 ID。给线程名称我们比线程 id 更有意义。

关于java - ForkJoinPool,如何打印出每个工作线程的ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35678415/

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