Callable and future implementations invoke tasks and return result data

Source: Internet
Author: User
Tags sleep
It programmer development Essentials-all kinds of resources download list, history of the most IT resources, personal collection summary.
1. The result type obtained by the future and the result type returned by callable must be identical, which is achieved by generics.
2, callable to use the Executorsevice Submit method submitted, the return of the future object can cancel the task.
3. Completionservice is used to submit a set of callable tasks whose take method returns the corresponding future object for a completed callable task.
(1) Like I planted several pieces of wheat at the same time, and waited for the harvest. When the harvest is ripe, it is the first to reap the wheat.

Example program:

Package edu.java5.threadpool;
Import Java.util.Random;
Import java.util.concurrent.Callable;
Import Java.util.concurrent.CompletionService;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ExecutorCompletionService;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.Future; public class Callableandfuture {public static void main (string[] args) {Executorservice ThreadPool = Executor
         S.newsinglethreadexecutor ();
          /* * ThreadPool's Execute (Runnable) method call cannot return results, the submit (callable) method call can return the result, * The returned result is encapsulated in the future object */future<string> future = Threadpool.submit (new callable<string> () {@Override public String C
				All () throws Exception {Thread.Sleep (2000);
			return "Hello";
         }
		 });
         System.out.println ("Waiting for results ..."); by calling Future.get () to get the result, the code below the try {//future.get () must be obtained before it can be executed System.out.println ("Get Results:" +future.Get ());
		System.out.println ("Already made!");
		} catch (Interruptedexception e) {e.printstacktrace ();
		} catch (Executionexception e) {e.printstacktrace (); 
		 /** * Completionservice is used to submit a set of callable tasks whose take method returns a future object corresponding to a completed callable task.
		**/Executorservice threadPool2 = Executors.newfixedthreadpool (10);
		completionservice<integer> completionservice = new executorcompletionservice<integer> (threadPool2);
			for (int i = 0; i < ten; i++) {final int seq = i; Completionservice.submit (New callable<integer> () {@Override public Integer call () throws Exception {T
					Hread.sleep (New Random (). Nextint (6000));
					System.out.println (Thread.CurrentThread (). GetName () + "execute the callable and return" +SEQ);
				return seq;
		}
			});
			} for (int i = 0; i < i++) {try {System.err.println (Completionservice.take (). get ());
			} catch (Interruptedexception e) {e.printstacktrace (); } catch (Executionexception e) {E. Printstacktrace (); }} System.out.println ("all finished.
	");
 }

}
Output:

Wait for the result
... Get results: Hello
has been made!
Pool-2-thread-6 execute the callable and return 5
5
pool-2-thread-8 Execute the callable and return 7
7
PO Ol-2-thread-9 execute the callable and return 8
8
pool-2-thread-10 Execute the callable and return 9
9
PO Ol-2-thread-2 execute the callable and return 1
1
pool-2-thread-5 execute the callable and return 4
4
Pool-2-thread-1 execute the callable and return 0
0
pool-2-thread-7 Execute the callable and return 6
6
  pool-2-thread-3 execute the callable and return 2
2
pool-2-thread-4 execute the callable and return 3
3
   are all taken out.



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.