Generates a return value from the thread--callable interface

Source: Internet
Author: User

Runnable is a standalone thread that performs work, but it does not return any values. If you want the thread to return a value when it is finished, you can implement the callable interface instead of the Runnable interface. The callable introduced in Java SE5 is a generic type parameter with a type parameter that represents the value returned from the method call () (instead of Run ()) and must use the Executorservice.submit () method Call it.

Thread Code:
publicclass ResulttThread implements Callable<String> {    privateint id;    public ResulttThread(int id) {        this.id = id;    }    @Override    public String call() throws Exception {        return"The result id is " + id;    }}
Calling code:
 Future<String> future; ExecutorService mService = Executors.newCachedThreadPool();    for (int05; i++) {       future = mService.submit(new ResulttThread(i));       System.out.println(future.get());    }
Operation Result:

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Generates a return value from the thread--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.