How to return object from Callable()

后端 未结 3 881
再見小時候
再見小時候 2020-12-11 17:08

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 ArrayMultip         


        
3条回答
  •  青春惊慌失措
    2020-12-11 17:44

    Adding to Joseph Ottinger's answer, to pass values to be used inside Callable's call() method, you can use closures:

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

提交回复
热议问题