How Java multithreading and concurrent processing threads -8.4 achieve the return value

We know that to run method of mass participation in three ways, namely:

  • The constructor parameter passing
  • Member variable parameter passing
  • The callback function parameters

How to deal with the return value of the thread?
Thread on the return value is a sore point. Since the implementation of some of our programs, the return value is dependent on the sub-tasks performed when the child handed over to the child thread to perform the task, is the need to get the value of their return, this time how to do? What method returns a value that is realized subtasks that?
The way to achieve mainly three kinds:
(1) the main thread wait method, that we can make the main thread loop to wait until the target child thread returns the result.
Without waiting for the time to look, what the results:
Here Insert Picture Description
From this result may know, according to the original multi-threaded this way, we can not wait for the precise control of our sub-task when it returns the results to the next statement . In other words, our main thread after calling the start method to execute multiple threads to execute immediately print statements, and this time value has not been assigned, we can not get the return value of subtasks.
Then how to rely on the return value of the sub-thread of it? We can use the main thread wait method, as follows:
Here Insert Picture Description
the main thread wait method, simple to implement, the disadvantage is the need to achieve their own circular logic to wait, and when to wait more than one variable, the code would be extremely bloated, and the need to loop How long is uncertain, we can not achieve precise control.
(2) join Thread class () blocks the current thread to wait for the child thread processed.
Here Insert Picture Description
join method can achieve more accurate method than the main thread wait control, simpler to implement, but the drawback is that it is not enough fine particle size.
(3) Callable interface by: FutureTask or acquired by the thread pool.
The first: the return value FutureTask obtaining
a new class Callable interface, named MyCallable,

package thread;

import java.util.concurrent.Callable;

public class MyCallable implements Callable<String>{
	@Override
	public String call() throws Exception {
		String value = "test";
		System.out.println("Ready to work");
		Thread.currentThread().sleep(5000);
		System.out.println("task done");
		return value;
	}
}

Then create a test class:
Here Insert Picture Description
second: get through the thread pool
Here Insert Picture Description
thread pool benefit is that we can submit more than one class that implements the Callable interface, to make the thread pool concurrently processing results, so that you can help us in these Callable implementation classes do unified management.

Guess you like

Origin blog.csdn.net/tanwenfang/article/details/92394950