Java multithreaded Programming (ii)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.