Java Callable interface--a thread with a return value

Source: Internet
Author: User

In the actual development process, we often need to wait for a batch of threads to return the results before continuing execution. "Thread Waiting for--countdownlatch use" we introduced the use of Countdownlatch, by using Countdownlatch, you can implement thread waiting.

JDK 1.8 implements a better way to implement thread wait and get thread return value, that is the callable interface, let's take a look at the specific code.

 PackageCom.coshaho.learn;ImportJava.util.Random;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;ImportOrg.apache.kafka.common.group.Time; Public classcallablelearn{ Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {LongStart =System.currenttimemillis (); Mycallabletask Task1=NewMycallabletask (); Mycallabletask Task2=NewMycallabletask (); Mycallabletask Task3=NewMycallabletask (); //you can get the return value using the thread Submit methodFuture<string> Future1 =Fixed_threadpool.submit (TASK1); Future<String> Future2 =Fixed_threadpool.submit (TASK2); Future<String> future3 =Fixed_threadpool.submit (TASK3); LongEnd =System.currenttimemillis (); //Task commit does not blockSYSTEM.OUT.PRINTLN ("Submit Task Cost" + (End-start) + "Ms."); System.out.println ("Task1:" +future1.get ()); System.out.println ("Task2:" +future2.get ()); System.out.println ("TASK3:" +future3.get ()); //Future.get method waits for a thread to return a valueSYSTEM.OUT.PRINTLN ("Get Task return value cost" + (System.currenttimemillis ()-end) + "Ms."); }        //a thread pool of size 3     Public Final StaticExecutorservice Fixed_threadpool = Executors.newfixedthreadpool (3);  Public Static classMycallabletaskImplementsCallable<string>    {        //sleep I seconds and return information@Override PublicString Call ()throwsException {random random=NewRandom (); inti = Random.nextint (10) * 1000;            Time.sleep (i); return"Sleep" + i + "Ms."; }            }}


Results

Submit task cost 3ms.
Task1:sleep 5000ms.
Task2:sleep 8000ms.
Task3:sleep 8000ms.
Get task return value cost 8659ms.

Three key points

1. Thread needs to implement callable interface

2. The thread pool submits the task using the Submit method, which can get the return value of the future

3. When using the Future.get method, the current thread is blocked, waiting for the task to return a value

Java Callable interface--a thread with a return value

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.