This article describes how to submit a task to the thread pool and get the result of the task's execution. It then simulates how the thread in the thread pool throws an exception during the execution of the task.
One, the thread class that performs the specific task
To get the execution result of a thread, you implement the callable interface. Factorialcalculator calculates the factorial of number, implemented as follows:
1 Importjava.util.concurrent.Callable;2 ImportJava.util.concurrent.TimeUnit;3 4 /**5 * Created by Administrator on 2017/9/26.6 */7 Public classFactorialcalculatorImplementsCallable<integer> {8 9 PrivateInteger number;Ten One PublicFactorialcalculator (Integer number) { A This. Number =Number ; - } - PublicInteger Call ()throwsException { the intresult = 1; - - if(number = = 0 | | number = = 1) { -result = 1; +}Else { - for(inti = 2; I < number; i++) { +Result *=i; ATimeUnit.MICROSECONDS.sleep (200); at if(i = = 5) { - Throw NewIllegalArgumentException ("Excepion happend");//calculating a factorial of more than 5 throws an exception. Annotate the IF statement as needed - } - } - } -System.out.printf ("%s:%d\n", Thread.CurrentThread (). GetName (), result); in returnresult; - } to}
The IF statement above 23 lines--25 indicates that if number is greater than 5, then if (i==5) is true, an exception is thrown. That is, when the simulation executes more than 5 factorial, an exception is thrown.
Second, the main class that submitted the task
Here's a look at how to submit a task to the thread pool and get the results of the task's return. We've committed 10 tasks to the thread pool, so we've created a ArrayList to save the execution results for each task.
In the first row, you first create a thread pool. The second line, where you create the list to save the execution results of 10 threads, each task calculates the factorial, so the thread returns an Integer. And this result as long as calculated, is put in future<integer> inside.
第5-7, randomly generates an integer within 10, and then creates a Factorialcalculator object that is the task to be executed and submits it through the thread pool's Submit method on line 8th.
1Threadpoolexecutor executor =(Threadpoolexecutor) Executors.newcachedthreadpool ();2List<future<integer>> resultlist =NewArraylist<future<integer>>();3Random random =NewRandom ();4 for(inti = 0; I < 10; i + +) {5 intRand = Random.nextint (10);6 7Factorialcalculator Factorialcalculator =NewFactorialcalculator (rand);8future<integer> res = executor.submit (factorialcalculator);//asynchronous commit, non blocking.9 Resultlist.add (res);Ten}
Note that thesubmit method is a non-blocking method , refer to this article. After the task is submitted, the thread in the threads pool is responsible for executing the task, and the results obtained after execution are eventually saved in Future<integer> , as shown in line 8th.
As soon as we invoke the The Submit () method of Executorservice the callable is handed over to Executorservice to execute.
The submit () is not blocking.
For each callable, we get a future object to get the result later.
Next, in the Do loop, we check the status of the task---whether it is done.
1 Do {2 //System.out.printf ("Number of completed tasks:%d\n", Executor.getcompletedtaskcount ());3 for(inti = 0; I < resultlist.size (); i++) {4future<integer> result =Resultlist.get (i);5System.out.printf ("Task%d:%s \ n", I, Result.isdone ());6 }7 Try {8TimeUnit.MILLISECONDS.sleep (50);9 Ten}Catch(interruptedexception e) { One e.printstacktrace (); A } -} while(Executor.getcompletedtaskcount () < resultlist.size ());
第3-6 the line for loop, remove each future<integer> from the ArrayList, and view its status IsDone (), that is, whether the execution is complete.
Line 13th, while end condition: Exits the Do loop when all threads have finished executing. Note: When the thread throws an exception during execution, it also indicates that the thread has finished executing.
Gets the execution result of the thread
1System.out.println ("Results as Folloers:");2 for(inti = 0; I < resultlist.size (); i++) {3future<integer> result =Resultlist.get (i);4Integer number =NULL;5 6 Try {7Number = Result.get ();//Blocking Method8}Catch(interruptedexception e) {9 e.printstacktrace ();Ten}Catch(executionexception e) { One e.printstacktrace (); A } -System.out.printf ("Task:%d, result%d:\n"), I, number); -}
Line 3rd takes out each stored result: future<integer>, line 7th Gets the result of the task from the future<integer>. the Future.get method is a blocking method . But in the front of the Do-while loop, we have checked to see if the execution of the task is complete, so we can quickly get the execution results out of the task.
We is invoking the Get () method of the future to get the result. Here we had to remember that, the Get () is a blocking method.
If the task throws an exception during execution, the final future<integer> get () returns NULL. However, it does not affect the execution of main thread---main threads.
The entire main class code is as follows:
Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.Random;Importjava.util.concurrent.*;/*** Created by Administrator on 2017/9/26.*/ Public classMain { Public Static voidMain (string[] args) {Threadpoolexecutor executor=(Threadpoolexecutor) Executors.newcachedthreadpool (); List<Future<Integer>> resultlist =NewArraylist<future<integer>>(); Random Random=NewRandom (); for(inti = 0; I < 10; i + +) { intRand = Random.nextint (10); Factorialcalculator Factorialcalculator=NewFactorialcalculator (RAND); Future<Integer> res = executor.submit (factorialcalculator);//asynchronous commit, non blocking.Resultlist.add (RES); } //In loop check out the result is finished Do {//System.out.printf ("Number of completed tasks:%d\n", Executor.getcompletedtaskcount ()); for(inti = 0; I < resultlist.size (); i++) { future<Integer> result =Resultlist.get (i); System.out.printf ("Task%d:%s \ n", I, Result.isdone ()); } Try{TimeUnit.MILLISECONDS.sleep (50); } Catch(interruptedexception e) {e.printstacktrace (); } } while(Executor.getcompletedtaskcount () <resultlist.size ()); System.out.println ("Results as Folloers:"); for(inti = 0; I < resultlist.size (); i++) { future<Integer> result =Resultlist.get (i); Integer Number=NULL; Try{ number= Result.get ();//Blocking Method}Catch(interruptedexception e) {e.printstacktrace (); } Catch (executionexception e) { e.printstacktrace (); } System.out.printf ("Task:%d, result%d:\n", I, number); } executor.shutdown (); }}
In the above number = Result.get (); Statement, we catch two exceptions, one is interruptedexception and the other is executionexception. Because we get the execution result of the task within the main thread, the main thread execution Result.get () blocks and throws interruptedexception if it is interrupted by (another thread) during the blocking process.
If an exception is thrown during the execution of the task (such as IllegalArgumentException), then the main thread will catch to executionexception here. At this point, you can "process" the task that throws the exception.
The results returned by Task1, Task2, and TASK4 in the figure are empty, indicating that they throw a illegalargumentexception exception.
For exceptions to be handled, refer to: Java thread pool exception handling best practices and this article.
Resources
"Java 7 Concurrency Cookbook" Chapter 4
Original: http://www.cnblogs.com/hapjin/p/7599189.html
JAVA line Cheng callable return results