java.lang.Thread无法强制转换为java.util.concurrent.ForkJoinWorkerThread

str*_*vil 5 java exception

我正在使用Java SE 7中的RecursiveTask测试Fibonacci示例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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,该程序会抛出运行时异常

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)
Run Code Online (Sandbox Code Playgroud)

我搜索了这个问题,但无法弄清楚问题.

谢谢你的帮助.

================

解:

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);
        }
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 7

你在滥用ForkJoinTask.

的ForkJoinTasks点是一个内执行他们ForkJoinPool.
池将compute()在其ForkJoinWorkerThreads中为您调用任务的方法.

你不应该compute()直接打电话.