"Multithreading implementation Scenario three: Implementing Callable Interface"

Source: Internet
Author: User

How to implement multithreading three:

A: Create a thread pool object that controls the creation of several thread objects.

public static Executorservice newfixedthreadpool (int nthreads)

B: Do a class to implement the callable interface.

C: Call the following method to

Future<?> Submit (Runnable Task)

<T> future<t> Submit (callable<t> Task)

D: I'm going to end it, okay?

OK.

 Packagecom.test;Importjava.util.concurrent.Callable; Public classMycallableImplementsCallable<integer> {    Private intNumber ;  PublicMycallable (intNumber ) {         This. Number =Number ; } @Override PublicInteger Call ()throwsException {intsum = 0;  for(intx=1;x<=number;x++) {sum+=x; }        returnsum; }}
 Packagecom.test;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classCallabletest { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {/**To create a thread pool object*/Executorservice Pool= Executors.newfixedthreadpool (2); /**can execute Runnable object or thread represented by callable object*/ Future<Integer> f1 = Pool.submit (NewMycallable (100)); Future<Integer> F2 = Pool.submit (NewMycallable (200)); /**V get ()*/Integer I1=F1.get (); Integer I2=F2.get ();        System.out.println (I1);        System.out.println (I2); /**End*/Pool.shutdown (); }}

Operation Result:

505020100

"Multithreading implementation Scenario three: Implementing Callable Interface"

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.