Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

java - How to return object from Callable()

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...