Here's some code demonstrating use of the Callable<> interface:
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]));
}
}
}
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…