小编典典

如何从Callable()返回对象

java

我正在尝试从call()返回2D数组,但遇到了一些问题。到目前为止,我的代码是:

//this is the end of main   
Thread t1 = new Thread(new ArrayMultiplication(Array1, Array2, length));
t1.start(); 
}

    public int[][] call(int[][] answer)
    {

    int[][] answer = new int[length][length];

    answer = multiplyArray(Array1, Array2, length); //off to another function which returns the answer to here

    return answer;                                  
    }

这段代码会编译,这不会返回我的数组。我确定我可能使用了错误的语法,但是找不到任何好的示例。

编辑:改变了一点


阅读 216

收藏
2020-10-16

共1个答案

小编典典

添加到Joseph Ottinger的答案中,要传递要在Callable的call()方法中使用的值,可以使用闭包:

    public static Callable<Integer[][]> getMultiplierCallable(final int[][] xs,
            final int[][] ys, final int length) {
        return new Callable<Integer[][]>() {
            public Integer[][] call() throws Exception {
                Integer[][] answer = new Integer[length][length];
                answer = multiplyArray(xs, ys, length);
                return answer;
            }
        };
    }

    public static void main(final String[] args) throws ExecutionException,
            InterruptedException {
        final int[][] xs = {{1, 2}, {3, 4}};
        final int[][] ys = {{1, 2}, {3, 4}};
        final Callable<Integer[][]> callable = getMultiplierCallable(xs, ys, 2);
        final ExecutorService service = Executors.newFixedThreadPool(2);
        final Future<Integer[][]> result = service.submit(callable);
        final Integer[][] intArray = result.get();
        for (final Integer[] element : intArray) {
            System.out.println(Arrays.toString(element));
        }
    }
2020-10-16