如何从 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;
}
此代码编译,这不返回我的数组。我确信我可能使用了错误的语法,但我找不到任何好的例子。
编辑:稍微改变一下
I'm trying to return a 2d array from call(), I'm having some issues. My code so far is:
//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;
}
This code compiles, this is not returning my array. I'm sure I'm probably using the wrong syntax, but I can't find any good examples.
EDIT: changed it a bit
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面是一些代码,演示了 Callable<> 的使用接口:
它的作用是构造一个可以提交给执行器服务的对象。它本质上与 Runnable 相同,只是它可以返回一个值;我们在这里所做的是创建一个具有两个线程的 ExecutorService,然后将此可调用对象提交给该服务。
接下来发生的事情是结果。get(),它将阻止直到可可返回。
您可能不应该自己进行线程管理。
Here's some code demonstrating use of the Callable<> interface:
What this does is construct an object that can be submitted to an executor service. It's fundamentally the same as a Runnable, except that it can return a value; what we're doing here is creating an ExecutorService with two threads, then submitting this callable to the service.
The next thing that happens is the result.get(), which will block until the callable returns.
You probably shouldn't do the Thread management yourself.
添加到 Joseph Ottinger 的答案中,要传递要在 Callable 的 call() 方法中使用的值,您可以使用闭包:
Adding to Joseph Ottinger's answer, to pass values to be used inside Callable's call() method, you can use closures:
除了 Joseph 的出色回答之外,请注意您的方法签名是
int[][] call(int[][])
。如果您引用Callable
javadoc,您将看到Callable
的call()
方法不接受任何参数。因此,您的方法是重载,而不是覆盖,因此不会被调用 Callable 的 call() 方法的任何内容调用。In addition to Joseph's excellent answer, note that your method signature is
int[][] call(int[][])
. If you reference theCallable
javadoc you'll see that theCallable
'scall()
method does not take any arguments. So your method is an overload, not an override, and so won't be called by anything that is callingCallable
'scall()
method.