我理解fork / join的概念,但几乎所有的互联网资源都使用Fibonacci作为例子,但我的场景更复杂。我勾画了程序,我在下面的代码中有一个例外。
Class Test
{
public static void main(String[] args)
{
ForkJoinPool p= new ForkJoinPool(5);
p.invoke(new Train());
}
}
Class Train extends RecursiveAction
{
public Train(int d, int n)
{
//some intialization
}
public Train()
{
t= new Train[5];
new Vec().run_Vec(t);
}
@Override
protected void compute() {
for(int i= 1; i< 8; i++)
{
// x, and y are predefined
temp[x][y] = some calculation;
}
}
}
class Vec
{
public void run_Vec(Train[] t) {
for (int i = 0; i < 5; i++) {
t[i] = new Train(i*4, i/2);
t[i].fork(); // error java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
}
for (int i = 0; i < 5; i++) {
t[i].join();
}
}
}
}
答案 0 :(得分:1)
我认为你的问题是由于从主线程调用fork()。当你调用p.invoke(new Train())时,你的默认列车构造函数实际调用run_vec()并尝试fork()。在阅读javadocs时,有一些例子在compute()中调用fork()。您需要从p.invoke()启动的线程中调用fork。
答案 1 :(得分:0)
根据这篇Java文章,我制作了以下代码片段:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveAction.html
你应该只在“正在运行”的线程中调用fork
(spawn)。这意味着您必须在compute
方法中传递Train数组:
package ...;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
class ConcurrentTest {
public static void main(String[] args) {
ForkJoinPool p= new ForkJoinPool(5);
p.invoke(new Train());
}
public static class Train extends RecursiveAction {
private Train[] t = null;
public Train(int d, int n) {
//some code
}
public Train() {
t= new Train[5];
}
@Override
protected void compute() {
if(t != null) {
new Vec().run_Vec(t);
for(int i= 1; i< 8; i++) {
System.out.println("Test.Train.compute(): " + i);
}
}
}
}
public static class Vec
{
public void run_Vec(Train[] t) {
for (int i = 0; i < 5; i++) {
t[i] = new Train(i*4, i/2);
System.out.println("Clazz: " + t[i].getClass());
t[i].fork(); // error java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
}
for (int i = 0; i < 5; i++) {
t[i].join();
}
}
}
}