无法将java.lang.Thread强制转换为java.util.concurrent.ForkJoinWorkerThread [英] java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
问题描述
我正在Java SE 7中使用RecursiveTask测试Fibonacci示例 http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveTask.html 。
I am testing the Fibonacci example using RecursiveTask in Java SE 7 http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveTask.html.
程序如下:
import java.util.concurrent.*;
public class testfuture{
public static void main(String[] args) {
System.out.println("Hello, World");
Fibonacci fib = new Fibonacci(10);
int result = fib.compute();
System.out.println(result);
}
}
class Fibonacci extends RecursiveTask<Integer> {
final int n;
Fibonacci(int n) { this.n = n; }
public Integer compute() {
if (n <= 1)
return n;
Fibonacci f1 = new Fibonacci(n - 1);
f1.fork();
Fibonacci f2 = new Fibonacci(n - 2);
return f2.invoke() + f1.join();
}
}
但是,程序会抛出运行时异常
However, the program throws a run-time exception
Hello, World
Exception in thread "main" java.lang.ClassCastException: java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
at java.util.concurrent.ForkJoinTask.fork(Unknown Source)
at Fibonacci.compute(testfuture.java:21)
at testfuture.main(testfuture.java:9)
我在Google上搜索了此问题,但无法找出问题所在。
I googled about this issue but could not figure out the problem.
感谢您的帮助。
===============
================
解决方案:
public class testfuture{
public static void main(String[] args) {
System.out.println("Hello, World");
Fibonacci fib = new Fibonacci(10);
ForkJoinPool pool = new ForkJoinPool();
int result = pool.invoke(fib);
//int result = fib.compute(); //run-time exception
System.out.println(result);
}
}
推荐答案
您'正在滥用ForkJoinTask。
You're misusing ForkJoinTask.
ForkJoinTasks的重点是在ForkJoinPool 。
池将调用 compute()
方法
The point of ForkJoinTasks is to execute them within a ForkJoinPool.
The pool will call the compute()
methods of the tasks for you in its ForkJoinWorkerThreads.
您不应直接调用 compute()
。
这篇关于无法将java.lang.Thread强制转换为java.util.concurrent.ForkJoinWorkerThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!