Java implementation of threads of the way there are several ways? Thread with a return value of how to achieve?
In the development of Java threads, there are several ways to turn thread? If you need to get the information returned by a thread how to do? You can be achieved? Kaige through the source code and share with everyone Thread how the return value brought back.
A: no return value of type
1: Thread class inheritance
2: implement Runnable
Both are all commonly used code demo to capture it.
1: Thread class inheritance wording
Definition: the extends type requires a thread class, and then implement the run method of the thread class.
edit
2: implement Runnable wording:
Define a class that implements the interface Runable, re-run method.
New a thread object, using the constructor has parameters, the parameters are runnable. Then thread.start ()
edit
Two: with a return value
3: realized Callable <V> Interface
Steps:
Callable a class implements the interface, re-call method;
In the time of the call, there is need to use the reference structure FutureTask this class, and then use the thread has the reference structure.
The last task of calling the get method.
code show as below:
edit
operation result:
edit
Callable return value Source:
We start from FutureTask this class, because the return value is obtained from the FutureTask. Take a look at the class diagram:
edit
FutureTask realized RunnableFuture interfaces, RunnableFuture interface inherits the Future and Runnable interface.
edit
edit
We look RunnableFuture this interface, we found only one run value method of no return. Then, the data returned is the thread which class to achieve it? In fact FutureTask class inside. We take a look at FuntrueTask this category:
edit
A re-run method. Finally, there is a set result. Since there are set methods. Take a look at the demo task.get () method:
edit
Get with a return value to the method.
Thus, to achieve callable interfaces with a reason to return values that have been found.
4: Use a thread pool threads to create
The use of threads in the thread pool is created, you can have a return value, you can not return a value. Use Executory this top-level interface to deal with.
Let's take a look at the relationship Executor interface. As shown below:
edit
Which saw the familiar ThreadPoolExecutor and ScheduledThreadPoolExecutor
4.1: Using Executor create no return worth threads:
edit
Description: here with no return value, in fact, calls the run method of Runnable.
4.2: demo with a return value
Create a class that implements the Callable interface. As shown below:
edit
Through this interface, we know that there is a return value.
edit
Three: summary
Java thread has implemented four ways:
We are most familiar with no two kinds of value in exchange as well as with two ways to return value. They are:
Thread, Runnable and Callable and thread pool