I. Overview
So far, we have been able to declare and make a thread task run up. But there is a problem: the tasks defined now do not have any return values, so join us to let me know when a task runs and tell me a result, the result table name task executes successfully or fails, what should I do at this time?
The answer is to use callable. Previously defined tasks are directly implemented with Runnable, and the Run method of the interface has no return value. The callable call method can return data of the corresponding type based on the generic parameter you passed in.
Second, the realization
1. Implement the callable interface to define thread tasks that can return results
Public class Implements Callable<string>{ privateint ID; Public taskcallable (int ID) { this. ID= id; } @Override Publicthrows Exception { return "Result of" Taskwithresult "+ID; }}
Note that the generic parameter string represents the type of the result that was returned after the task was executed.
2. Give the task to the thread performer, executor, to have the agent execute these threads
Executorservice exec = Executors.newcachedthreadpool (); // Foreman ArrayList New Arraylist<future<string>> (); // for (int i = 0; i < i++) { results.add (exec.submit (new taskcallable (i))); Submit Returns a future that represents the result to be returned }
Note that you need to use Executor's Submit method to invoke call callable.
The method returns an object of the future interface whose generic parameter represents the type of parameter the call method will return.
3.Future type
The next future type is simply understood: by name, the type object represents the result of the thread execution, so it is called the future. Then, when you get the result of the thread that the type holds, it is possible that the thread is not running, so it is called a "future result."
- First, you can use the Isdone () method to query whether the future is complete, and when the task is complete, you can call the Get () method to get the result
- If the Get method is called directly without judgment, then if the thread is not completed, get will block until the result is ready
Java multithreading--< three > Let line threads return value