Multithreading in Java multithreaded Programming (a) does not return a value, this article describes multithreading with return values.
To have a return value, you need to implement a new interface callable instead of the Runnable interface, the implemented method is also changed to the call () method, the executor is no longer called execute (), but the Submit ()
"Program Instance"
1 Public classTaskwithresultImplementsCallable<string> {2 3 Private intID;4 5 PublicTaskwithresult (intID) {6 This. ID =ID;7 }8 9 @OverrideTen PublicString Call ()throwsException { One return"Result of Taskwithresult" + ID + ": sum () =" +Sum (ID); A } - - Private intSum (intID) { the return(ID * (ID + 1))/2; - } - -}
1 Public classMain {2 3 Public Static voidMain (string[] args) {4Executorservice exec =Executors.newcachedthreadpool ();5arraylist<future<string>> results =NewArraylist<future<string>>();6 for(inti = 0; I < 10; i++)7Results.add (Exec.submit (NewTaskwithresult (i)));8 for(future<string>fs:results)9 Try {Ten System.out.println (Fs.get ()); One}Catch(interruptedexception e) { A System.out.println (e); - return; -}Catch(executionexception e) { the System.out.println (e); -}finally { - Exec.shutdown (); - } + } - +}
"Run Results"
1 result of Taskwithresult 0:sum () = 0 2 result of Taskwithresult 1:sum () = 1 3 result of Taskwithresult 2:sum () = 3 4 result of Taskwithresult 3:sum () = 6 5 result of Taskwithresult 4:sum () = 6 result of Taskwithresult 5:sum () = 7 result of Taskwithresult 6:sum () = 8 r Esult of Taskwithresult 7:sum () = 9 result of Taskwithresult 8:sum () =Ten result of Taskwithres Ult 9:sum () = 45
Java multithreaded Programming (ii)