如何从Callable()返回对象

我正试图从call()返回一个二维数组,我遇到了一些问题。 到目前为止我的代码是:

//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; } 

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

编辑:改变了一下

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

  public static Callable getMultiplierCallable(final int[][] xs, final int[][] ys, final int length) { return new Callable() { 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 callable = getMultiplierCallable(xs, ys, 2); final ExecutorService service = Executors.newFixedThreadPool(2); final Future result = service.submit(callable); final Integer[][] intArray = result.get(); for (final Integer[] element : intArray) { System.out.println(Arrays.toString(element)); } } 

这里有一些代码演示了Callable <>接口的用法:

 public class test { public static void main(String[] args) throws ExecutionException, InterruptedException { Callable callable = new Callable() { @Override public int[][] call() throws Exception { int[][] array = new int[5][]; for (int i = 0; i < array.length; i++) { array[i] = new int[]{5 * i, 5 * i + 1, 5 * i + 2, 5 * i + 3}; } return array; } }; ExecutorService service = Executors.newFixedThreadPool(2); Future result = service.submit(callable); int[][] intArray = result.get(); for (int i = 0; i < intArray.length; i++) { System.out.println(Arrays.toString(intArray[i])); } } } 

这样做是构造一个可以提交给执行者服务的对象。 它与Runnable基本相同,只是它可以返回一个值; 我们在这里做的是创建一个带有两个线程的ExecutorService,然后将这个callable提交给服务。

接下来发生的事情是result.get(),它将阻塞直到callable返回。

你可能不应该自己做Thread管理。

除了Joseph的优秀答案之外,请注意您的方法签名是int[][] call(int[][]) 。 如果你引用Callable javadoc,你会看到Callablecall()方法不带任何参数。 所以你的方法是一个重载,而不是覆盖,因此不会被调用Callablecall()方法的任何东西调用。