use*_*309 7 java multithreading 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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码编译,这不是返回我的数组.我确定我可能使用了错误的语法,但我找不到任何好的例子.
编辑:改了一下
这里有一些代码演示了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<int[][]> result = service.submit(callable);
int[][] intArray = result.get();
for (int i = 0; i < intArray.length; i++) {
System.out.println(Arrays.toString(intArray[i]));
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样做是构造一个可以提交给执行者服务的对象.它与Runnable基本相同,只是它可以返回一个值; 我们在这里做的是创建一个带有两个线程的ExecutorService,然后将这个callable提交给服务.
接下来发生的事情是result.get(),它将阻塞直到callable返回.
你可能不应该自己做Thread管理.
添加到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));
}
}
Run Code Online (Sandbox Code Playgroud)