Java thread (18): new feature-threads with returned values

Source: Internet
Author: User

Java thread: new feature-a thread with a return value has no return value before Java 5. It often takes a long time to get a return value for "yes", and the code is hard to write. Or simply bypass this hurdle and go another way. Now Java finally has a task that can return values (also called a thread. The Callable interface must be implemented for a task that can return values. Similarly, a task without a return value must be a Runnable interface. After executing the Callable task, you can obtain a Future Object. On this Object, you can call get to obtain the Object returned by the Callable task. The following is a simple example: import java. util. concurrent. *;/*** Java thread: thread with returned values ** @ author Administrator 0:41:50 */public class Test {public static void main (String [] args) throws ExecutionException, interruptedException {// create a thread pool ExecutorService pool = Executors. newFixedThreadPool (2); // create two tasks with returned values: Callable c1 = new MyCallable ("A"); Callable c2 = new MyCallable ("B "); // execute the task and obtain the Future object Future f1 = Pool. submit (c1); Future f2 = pool. submit (c2); // obtain the return value of the task from the Future object and output it to the console System. out. println (">>>" + f1.get (). toString (); System. out. println (">>>" + f2.get (). toString (); // close the thread pool. shutdown () ;}} class MyCallable implements Callable {private String oid; MyCallable (String oid) {this. oid = oid ;}@ Override public Object call () throws Exception {return oid + "content returned by the task" ;}>> content returned by task A >>> returned by Task B Process finished with exit code 0 is very simple. For more information, see the APIs of Callable and ure interfaces.

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.